Declaring and Initializing Variables – Declarations

Declaring and Initializing Variables

Variable declarations (technically called declaration statements) are used to declare variables, meaning they are used to specify the type and the name of variables. This implicitly determines their memory allocation and the values that can be stored in them. Examples of declaring variables that can store primitive values follow:

Click here to view code image

char a, b, c;            // a, b, and c are character variables.
double area;             // area is a floating-point variable.
boolean flag;            // flag is a boolean variable.

The first declaration is equivalent to the following three declarations:

char a;
char b;
char c;

A declaration can also be combined with an initialization expression to specify an appropriate initial value for the variable.

Click here to view code image

int i = 10,              // i is an int variable with initial value 10.
    j = 0b101;           // j is an int variable with initial value 5.
long big = 2147483648L;   // big is a long variable with specified initial value.

Reference Variables

A reference variable can store the reference value of an object, and can be used to manipulate the object denoted by the reference value.

A variable declaration that specifies a reference type (i.e., a class, an array, an interface name, or an enum type) declares a reference variable. Analogous to the declaration of variables of primitive data types, the simplest form of reference variable declaration specifies the name and the reference type only. The declaration determines which objects can be referenced by a reference variable. Before we can use a reference variable to manipulate an object, it must be declared and initialized with the reference value of the object.

Click here to view code image

Pizza yummyPizza;   // Variable yummyPizza can reference objects of class Pizza.
Hamburger bigOne,   // Variable bigOne can reference objects of class Hamburger,
          smallOne; // and so can variable smallOne.

It is important to note that the preceding declarations do not create any objects of class Pizza or Hamburger. Rather, they simply create variables that can store reference values of objects of the specified classes.

A declaration can also be combined with an initializer expression to create an object whose reference value can be assigned to the reference variable:

Click here to view code image

Pizza yummyPizza = new Pizza(“Hot&Spicy”); // Declaration statement

The reference variable yummyPizza can reference objects of class Pizza. The keyword new, together with the constructor call Pizza(“Hot&Spicy”), creates an object of the class Pizza. The reference value of this object is assigned to the variable yummyPizza. The newly created object of class Pizza can now be manipulated through the reference variable yummyPizza.