Java: Variables

Inside a class you can define variables. Unlike C++ many data types are now treated as instances of Classes (e.g. see String below) rather than as primitive types. The two kinds of variables are listed in the tables below.

Why would you want to use the Class type instead of the primitive type? One reason is that you may want to take advantage of the methods belonging to a Class. Another is that you can not tell they type of a variable if it is defined as a primitive type (you can ofcourse typecast it). However, you can tell the type of a variable if it is defined as a Class type using the instanceof operator.
Primitive Types

byte
  • Example: byte word;
  • Size = 8 bits.
short
  • Example: short num;
  • Size = 16 bits.
int
  • Example: int Year;
  • Size = 32 bits.
long
  • Example: long word;
  • Size = 64 bits.
float
  • Example: float time;
  • Size = 32 bits.
double
  • Example: double time;
  • Size = 64 bits.
char
  • Example: char symbol;
  • Size = 16 bits.
boolean
  • Example: boolean answer;
  • value= true or false (not a number as in C++).


Class Types (see book or documentation for details)

String
Example of Declarations:
String Name;
Name = "Lynne Grewe";

OR
String Name = new String("Lynne Grewe");

OR
String Name = "Lynne Grewe";


Boolean
Double
Float
Short
Byte
Long

Variables can be declared with a protection type or status that restricts who can access them. See the page on Protection Types for more information.
Exercise


Static Variables

If a variable is declared static it means that the value of this variable will be the same for any object instatiated from its class. For example,

class Document {
  static int version=10;
  .....
}

This means that any object instatiated from Document will have the same value of version. Whenevery any Document object changes the value of version it is changed for all instances of this object. This is somewhat like the concept of a global variable.

Note You can access a static variable through the class name or an instance of the class:

Document.version++;
Document d = new Document();
d.version = 7;



Exercise



Final Variables

This is akin to a constant in that it is set once and can never be changed. The value is set at declaration time as shown in the example below.

class Document {

   final int year 1997;
 .....
}