How to declare and initialize a variable

A variable in Java has a type, name and a value. A variable may store of value of either:
- a primitive data type such as int, boolean, char.
or
- a reference to an object, also called reference variable.


for example:
int i; //variable i that can store an int value.
boolean isDone; //Variable isDone that can store a boolean value.
//Variables a, f and r that can store a char value each:
char a,f,r;

//Equivalent to the three separate declarations:
char a;
char f;
char r;

What we just deed above is called variable declaration. By declaring variable we are implicitly allocating memory for these variables and determining the value types that can be stored in them.
So, in the example above, we named a variable: isDone that can store a boolean value, but not initialized yet.

Giving a variable a value when declared is called initialization. Further, we can declare and initialize a variable in one go. For example, we could have declared and initialized our variables of the previous example:

int i = 101; //variable i initialized with the value 101:
//variable isDone initialized with the boolean value true.
boolean isDone = true;
// variables a,f and r initialized with the values 'a','f' and 'r' //respectively:
char a = 'a', f='f', r='r';
//
equivalent to:
char a = 'a';
char f = 'f';
char r = 'r';


Analogous to declaring variables to denote primitive values, we can declare a variable denoting an object reference, that's; a variable having one of the following reference types: a class, an array, or an interface.

For instance (see also Class Instantiation ):
//declaring a redCar and a blueCar of class Car.
Car redCar, blueCar;

Please note that declarations above do not create any object of type Car. These are just variables that can store references to objects of class Car but no reference is created yet.

A reference variable has to be instantiated before being used. So:
// declaring and initializing the redCar reference variable
Car redCar=new Car("red");
An object of class Car is created using the keyword new together with the Constructor call Car("red"), then stored in the variable redCar which is now ready to be manipulated.

No comments: