Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 474


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Easy Java Lecture 5: Variables. Teach/learn online

Go to all tips in Java Lectures by Anatoliy Malyarenko

Variables

by: Anatoliy Malyarenko

Abstract

  • Contents of the lecture.
  • What is a variable?
  • Data types.
  • Scope.
  • Variable initialisation.
  • Final variables.
  • Summary of variables.

What is a variable?

An object stores its state in variables.

Definition 1. A variable is an item of data named by an identifier.

You must explicitly provide a name and a type for each variable you want to use in your program. The variable's name must be a legal identifier -- an unlimited series of Unicode characters that begins with a letter. You use the variable name to refer to the data that the
variable contains. The variable's type determines what values it can hold and what operations can be performed on it. To give a variable a type and a name, you write a variable declaration, which generally looks like this:

type name

In addition to the name and type that you explicitly give a variable, a variable has scope. The section of code where the variable's simple name can be used is the variable's scope. The variable's scope is determined implicitly by the location of the variable declaration, that is,
where the declaration appears in relation to other code elements.

The MaxVariablesDemo program, shown below, declares eight variables of different types within its main method.

Code:

public class MaxVariablesDemo {
   public static void main(String args[]) {
      // integers
      byte largestByte = Byte.MAX_VALUE;
      short largestShort = Short.MAX_VALUE;
      int largestInteger = Integer.MAX_VALUE;
      long largestLong = Long.MAX_VALUE;
      
      // real numbers
      float largestFloat = Float.MAX_VALUE;
      double largestDouble = Double.MAX_VALUE;

      // other primitive types
      char aChar = ’S’;
      boolean aBoolean = true;

      // display them all
      System.out.println("The largest byte value is "
                                       + largestByte);
      System.out.println("The largest short value is "
                                       + largestShort);
      System.out.println("The largest integer value is "
                                       + largestInteger);
      System.out.println("The largest long value is "
                                       + largestLong);
      System.out.println("The largest float value is "
                                       + largestFloat);
      System.out.println("The largest double value is "
                                       + largestDouble);
      if (Character.isUpperCase(aChar)) {
         System.out.println("The character " + aChar
                                    + " is upper case.");
      } else {
         System.out.println("The character " + aChar
                                    + " is lower case.");
      }
         System.out.println("The value of aBoolean is "
                                             + aBoolean);
   }
}
The output from this program is:

The largest byte value is 127
The largest short value is 32767
The largest integer value is 2147483647
The largest long value is 9223372036854775807
The largest float value is 3.40282e+38
The largest double value is 1.79769e+308
The character S is upper case.
The value of aBoolean is true

Data types

Every variable must have a data type. A variable's data type determines the values that the variable can contain and the operations that can be performed on it. For example, in the MaxVariablesDemo program, the declaration int largestInteger declares that largestInteger has an integer data type (int). Integers can contain only integral values (both positive and negative). You can perform arithmetic operations, such as addition, on integer variables.

The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a single value of the appropriate size and format for its type: a number, a character, or a boolean value. For example, an integer value is 32 bits of data in a format known as two's complement, the value of a char is 16 bits of data formatted as a Unicode character, and so on.

Primitive data types

Keyword Description Size
(integers)
    byte     Byte-length integer     8 bit
    short     Short integer     16 bit
    int     Integer     32 bit
    long     Long integer     64 bit
(real numbers)
    float     Single-precision floating point     32 bit
    double     Double-precision floating point     64 bit
(other types)
    char     A single character     16 bit
    boolean     A boolean value (true or false)     8 bit


Table 1: Primitive data types

In other languages, the format and size of primitive data types may depend on the platform on which a program is running. In contrast, the Java programming language specifies the size and format of its primitive data types. Hence, you don't have to worry about system-
dependencies.

You can put a literal primitive value directly in your code. For example, if you need to assign the value 4 to an integer variable you can write this:

int anInt = 4;

The digit 4 is a literal integer value. Here are some examples of literal values of various
primitive types:

Literal Data type
178 int
8864L long
37.266 double
37.266D double
87.363F float
26.77e3 double
'c' char
true boolean
false boolean

Generally speaking, a series of digits with no decimal point is typed as an integer. You can specify a long integer by putting an 'L' or 'l' after the number. 'L' is preferred as it cannot be confused with the digit '1'. A series of digits with a decimal point is of type double.

You can specify a float by putting an 'f' or 'F' after the number. A literal character value is any single Unicode character between single quote marks. The two boolean literals are simply true and false.

Arrays, classes, and interfaces are reference types. The value of a reference type variable, in contrast to that of a primitive type, is a reference to (an address of) the value or set of values represented by the variable.

A reference is called a pointer, or a memory address in other languages. The Java programming language does not support the explicit use of addresses like other languages do. You use the variable's name instead.

Variable names

A program refers to a variable's value by the variable's name. For example, when it displays the value of the largestByte variable, the MaxVariablesDemo program uses the name largestByte. A name, such as largestByte, that's composed of a single identifier, is
called a simple name. Simple names are in contrast to qualified names, which a class uses to refer to a member variable that's in another object or class.

In the Java programming language, the following must hold true for a simple name:

  • It must be a legal identifier. An identifier is an unlimited series of Unicode characters that begins with a letter.
  • It must not be a keyword, a boolean literal (true or false), or the reserved word null.
  • It must be unique within its scope. A variable may have the same name as a variable whose declaration appears in a different scope. In some situations, a variable may share the same name as another variable if it is declared within a nested block of code.

By convention variable names begin with a lowercase letter, and class names begin with an uppercase letter. If a variable name consists of more than one word, the words are joined together, and each word after the first begins with an uppercase letter, like this: isVisible.

The underscore character ( ) is acceptable anywhere in a name, but by convention is used only to separate words in constants (because
constants are all caps by convention and thus cannot be case-delimited).

Scope

A variable's scope is the region of a program within which the variable can be referred to by its simple name. Secondarily, scope also determines when the system creates and destroys memory for the variable. Scope is distinct from visibility, which applies only to member
variables and determines whether the variable can be used from outside of the class within which it is declared. Visibility is set with an access modifier.

The location of the variable declaration within your program establishes its scope and places it into one of these four categories:

  • member
  • variable
  • local variable
  • method parameter
  • exception-handler parameter

A member variable is a member of a class or an object. It is declared within a class but outside of any method or constructor. A member variable's scope is the entire declaration of the class. However, the declaration of a member needs to appear before it is used when the
use is in a member initialisation expression.

You declare local variables within a block of code. In general, the scope of a local variable extends from its declaration to the end of the code block in which it was declared. In MaxVariablesDemo, all of the variables declared within the main method are local variables.

The scope of each variable in that program extends from the declaration of the variable to the end of the main method -- indicated by the first right curly bracket } in the program code.

Parameters are formal arguments to methods or constructors and are used to pass values into methods and constructors. The scope of a parameter is the entire method or constructor for which it is a parameter.

Exception-handler parameters are similar to parameters but are arguments to an exception handler rather than to a method or a constructor. The scope of an exception-handler parameter is the code block between { and } that follow a catch statement.

Consider the following code sample:

Code:

if (...) {
   int i = 17;
   ...
}
// error<br />
System.out.println("The value of i = " + i);</p>

The final line won't compile because the local variable i is out of scope. The scope of i is the block of code between the { and }. The i variable does not exist anymore after the closing }. Either the variable declaration needs to be moved outside of the if statement block,
or the println method call needs to be moved into the if statement block.

Variable initialisation

Local variables and member variables can be initialised with an assignment statement when they're declared. The data type of the variable must match the data type of the value assigned to it. The MaxVariablesDemo program provides initial values for all its local variables
when they are declared. The local variable declarations from that program follow, with the initialisation code set in bold:

// integers
byte largestByte = Byte.MAX_VALUE;

short largestShort = Short.MAX_VALUE;

int largestInteger = Integer.MAX_VALUE;

long largestLong = Long.MAX_VALUE;

// real numbers
float largestFloat = Float.MAX_VALUE;

double largestDouble = Double.MAX_VALUE;

// other primitive types
char aChar = 'S';

boolean aBoolean = true;

Parameters and exception-handler parameters cannot be initialised in this way. The value for a parameter is set by the caller.

Final variables

You can declare a variable in any scope to be final. The value of a final variable cannot change after it has been initialised. Such variables are similar to constants in other programming languages.

To declare a final variable, use the final keyword in the variable declaration before the type:

final int aFinalVar = 0;

The previous statement declares a final variable and initialises it, all at once. Subsequent attempts to assign a value to aFinalVar result in a compiler error. You may, if necessary, defer initialisation of a final local variable. Simply declare the local variable and initialise it later, like
this:

Code:

final int blankfinal;
. . .
blankfinal = 0;

A final local variable that has been declared but not yet initialised is called a blank final. Again, once a final local variable has been initialised, it cannot be set, and any later attempts to assign a value to blankfinal result in a compile-time error.

Summary of variables

When you declare a variable, you explicitly set the variable's name and data type. The Java programming language has two categories of data types: primitive and reference. A variable of primitive type contains a value. All of the primitive data types along with their sizes
are shown in Table 1.

The location of a variable declaration implicitly sets the variable's scope, which determines what section of code may refer to the variable by its simple name. There are four categories of scope: member variable scope, local variable scope, parameter scope, and
exception-handler parameter scope.

You can provide an initial value for a variable within its declaration by using the assignment operator (=).

You can declare a variable as final. The value of a final variable cannot change after it's been initialised.

by Anatoliy Malyarenko


17717 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by Javaaddict on Monday, September 18, 2006 (18:00:00) (7151 reads)

Easy Java Lecture 4: OOP programming concepts: example. Teach/learn online

Go to all tips in Java Lectures by Anatoliy Malyarenko

Object-oriented programming concepts: example


by: Anatoliy Malyarenko

Abstract

In this lecture, you will learn, how the concepts of object-oriented programming can be implemented into Java code.


Preparation

Start RealJ. Create a new applet project named ClickMe. Close the project. Point you browser to
http://java.sun.com/docs/books/tutorial/java/concepts/practical.html

Download the files ClickMe.java and Spot.java to the folder where your project lives.
Open project and add file Spot.java to the project. Build and run applet. A red spot appears when you click the mouse within the applet's bounds.

Objects in the ClickMe applet

Many objects play a part in this applet. The two most obvious ones are the ones you can see: the applet itself and the spot, which is red on-screen.

The browser creates the applet object when it encounters the applet tag in the HTML code containing the applet. The applet tag provides the name of the class from which to create the applet object. In this case, the class name is ClickMe.

The ClickMe applet in turn creates an object to represent the spot on the screen. Every time you click the mouse in the applet, the applet moves the spot by changing the object's x and y location and repainting itself. The spot does not draw itself; the applet draws the spot, based on information contained within the spot object.

Besides these two obvious objects, other, non visibleobjects play a part in this applet. Three objects represent the three colours used in the applet (black, white, and red); an event object represents the user action of clicking the mouse, and so on.

Classes in the ClickMe applet

Because the object that represents the spot on the screen is very simple, let's look at its class, named Spot. It declares three instance variables: size contains the spot's radius, x contains the spot's current horizontal location, and y contains the spot's current vertical
location:

Code:

public class Spot {
   //instance variables
   public int size;
   public int x, y;
   //constructor
   public Spot(int intSize) {
      size = intSize;
      x = -1;
   y = -1;
   }
}

Additionally, the class has a constructor -- a subroutine used to initialise new objects created from the class. You can recognise a constructor because it has the same name as the class. The constructor initialises all three of the object's variables. The initial value of size is provided as an argument to the constructor by the caller. The x and y variables are set to -1 indicating that the spot is not on-screen when the applet starts up.

The applet creates a new spot object when the applet is initialised. Here's the relevant code from the applet class:

Code:
   
private Spot spot = null;
private static final int RADIUS = 7;
...
spot = new Spot(RADIUS);

The first line shown declares a variable named spot whose data type is Spot, the class from which the object is created, and initialises the variable to null. The second line declares an integer variable named RADIUS whose value is 7. Finally, the last line shown creates the object; new allocates memory space for the object. Spot(RADIUS) calls the constructor you saw previously and passes in the value of RADIUS. Thus the spot object's size is set to 7.

The figure on the left is a representation of the Spot class. The figure on the right is a spot object.

Messages in the ClickMe applet

As you know, object A can use a message to request that object B do something, and a message has three components:

  • The object to which the message is addressed.
  • The name of the method to perform.
  • Any parameters the method needs.

Here are a few lines of code from the ClickMe applet:

Code:

g.setColor(Color.white);
g.fillRect(0,
            0,
            getSize().width - 1,
            getSize().height - 1);

Both are messages from the applet to an object named g -- a Graphics object that knows how to draw simple on-screen shapes and text. This object is provided to the applet when the browser instructs the applet to draw itself. The first line sets the colour to white; the second fills a rectangle the size of the applet, thus painting the extent of the applet's area white.

The following figure highlights each message component in the first message:

Inheritance in the ClickMe applet

To run in a browser, an object must be an applet. This means that the object must be an instance of a class that derives from the Applet class provided by the Java platform.

The ClickMe applet object is an instance of the ClickMe class, which is declared like this:

Code:

public class ClickMe extends Applet
               implements MouseListener {               
   ...
}

The extends Applet clause makes ClickMe a subclass of Applet. ClickMe inherits a lot of capability from its superclass, including the ability to be initialised, started, and stopped by the browser, to draw within an area on a browser page, and to register to receive mouse
events. Along with these benefits, the ClickMe class has certain obligations: its painting code must be in a method called paint, its initialisation code must be in a method called init, and so on.

Code:

public void init() {
   ... // ClickMe’s initialisation code here
}
public void paint(Graphics g) {
   ... // ClickMe’s painting code here
}

Interfaces in the ClickMe applet

The ClickMe applet responds to mouse clicks by displaying a red spot at the click location. If an object wants to be notified of mouse clicks, the Java platform event system requires that the object implement the MouseListener interface. The object must also register
as a mouse listener.

The MouseListener interface declares five different methods each of which is called for a different kind of mouse event: when the mouse is clicked, when the mouse moves outside of the applet, and so on. Even though the applet is interested only in mouse clicks it must implement all five methods. The methods for the events that it isn't interested in are empty.

The complete code for the ClickMe applet is shown below.

Code:

import java.applet.Applet;
import java.awt.*;

import java.awt.event.*;

public class ClickMe extends Applet
      implements MouseListener {
   private Spot spot = null;
   private static final int RADIUS = 7;
   public void init() {
      addMouseListener(this);
   }

   public void paint(Graphics g) {
      // draw a black border
      // and a white background
      g.setColor(Color.white);
      g.fillRect(0,
                  0,
                  getSize().width - 1,
                  getSize().height - 1);
      g.setColor(Color.black);
      g.drawRect(0,
                  0,
                  getSize().width - 1,
                  getSize().height - 1);
      // draw the spot
      g.setColor(Color.red);
      if (spot != null) {
         g.fillOval(spot.x - RADIUS,
         spot.y - RADIUS,
         RADIUS * 2, RADIUS * 2);
      }      
   }
   public void mousePressed(MouseEvent event) {
      if (spot == null) {
         spot = new Spot(RADIUS);
      }
      spot.x = event.getX();
      spot.y = event.getY();
      repaint();
   }
   public void mouseClicked(MouseEvent event) {}
   public void mouseReleased(MouseEvent event){}
   public void mouseEntered(MouseEvent event) {}
   public void mouseExited(MouseEvent event) {}

API documentation

The ClickMe applet inherits a lot of capability from its superclass. To learn more about how ClickMe works, you need to learn about its superclass, Applet. How do you find that information? You can find detailed descriptions of every class in the API documentation, which
constitute the specification for the classes that make up the Java platform.

The API documentation for the Java 2 Platform is online at java.sun.com. It's helpful to have the API documentation for all releases you use bookmarked in your browser.

API documents for Java 2 Platform, Standard Edition, v1.4

To learn more about all the classes and interfaces from the Java platform used by the ClickMe applet, you can look at the API documentation for these classes:

Summary

This discussion glossed over many details and left some things unexplained, but you should have some understanding now of what object-oriented concepts look like in code. You should now have a general understanding of the following:

  • That a class is a prototype for objects.
  • That objects are created from classes.
  • That an object's class is its type.
  • How to create an object from a class?
  • What constructors are?
  • How to initialise objects?
  • What the code for a class looks like?
  • What class variables and methods are?
  • What instance variables and methods are?
  • How to find out what a class's superclass is?
  • That an interface is a protocol of behaviour.
  • What it means to implement an interface?

10502 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 0
Posted by Javaaddict on Friday, September 15, 2006 (18:00:00) (11457 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475|
474
| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394| 393| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy