Page 157 - Computer science 868 Class 12
P. 157
Declaration of a Variable
The compiler must know beforehand what type of value it is going to store or execute. The variable declaration tells
the compiler the name and the data type of a variable. It helps to generate the right code.
Syntax to declare a variable:
<data type> <space><name of the variable> [= <value>];
where [= <value>] is optional.
Let us see the following examples of variable declarations.
• int a;
• double b = 8.5;
• boolean b = true;
• float f = 3.6f;
• long l = 456743l;
• char ch = 'A';
• short s = 45;
• byte b = 2;
We can also declare more than one variable of the same data type together in the same statement.
For example,
int a, b;
double c = 9.8, d = 7.0;
Initialisation of a Variable
The variable definition assigns a variable a memory location and a value. This memory is randomly allocated to the
variable. The space which is assigned to the variable may or may not contain any previous value, also called a garbage
value. This garbage value must be removed before assigning a new value. Hence, we initialise some value to the
variable while defining it.
There are two ways to initialise a variable in Java. In other words, we can say that there are two types of initialisation
in Java. They are as follows:
• Static Initialisation: The assigning of values in a variable directly at the time of its declaration is called static initialisation.
For example:
int a = 5;
double b = 10.45;
char c = 'a';
String s = "India";
• Dynamic Initialisation: Sometimes, a variable needs to be initialised with some value while the program is executing.
This type of initialisation is called dynamic initialisation.
For example:
int a, b, c;
a = sc.nextInt();
b = sc.nextInt();
c = a + b; // Dynamic Initialisation
Final Variable
We assign some value to a variable for doing calculations. During the program, if it is required to change the value of
the variable, then it is maintained in the same location where the variable is declared. Let us see the procedure.
155
Variables and Expressions 155

