Variable
It is name given to the storage area or memory location and it’s value change during programming execution. The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier. In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here:
In java we can create two types of variables:
- Primitive Variable : This variable is created by using primitive datatype.
- Referenced Variable : This variable is creating by using referenced datatype.
Syntax:
type identifier [ = value][, identifier [= value] ...] ;
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and f.
Types of Variables
Java support three types of variable
1) Local Variable: A variable that is declared within a bracket is called local variable.
2) Instance Variable: A variable that is declared inside the class but outside the method is called as instance variable. it is not declared as static.
3) Static Variable: A variable that is declared as static is called static variable. It can not be local.
Dynamic Initialization of variable
Java allows variable to be initialized dynamically using any expression valid at the time the variable is declared.
int a=10; //Static
int a=2*2+10-8;
class DynamicIniti
{
public static void main(String args[])
{
double a=3.0, b=4.0;
//c is dynamically initialized
double c=Math.sqrt(a*a+b*b);
System.out.println("square is"+c);
}
}
O/P
g:\java>javac DynamicIniti
g:\java>java Dynamic
square is 5.0
The Scope and lifetime of variable
Whenever any variable declared within a scope or a bracket then it is known only within that bracket.
class Scope
{
public static void main(String args[])
{
int x; //known to call within main
x=10;
if(x==10) //start new scope
{
int y=10; //known only to this bracket
//x and y both are known here
System.out.println("x and y"+x+" "+y);
x=y*2;
}
// y=100;
System.out.println("x is"+x);
}
}
Constant in Java
Constant is an identifier whose value cannot be changed during program execution.
In java if you want to make the identifier as constant so you have to use the final keyword.
Final is a keyword which is very important for three things and they are variable, method, class.
If we want to make something non changeable during program execution so for that we have to make it as final.
Syntax.
final data type v1=val1, v2=val2.. ;
Example
final int a=20;
a=a+30; //invalid
O/P
g:\java>javac Scope.java
g:\java>java Scope
x and y 10 10
x is 20