Variable Types
•Example
inta,b,c;// Declares three int’s, a, b, and c.
inta =10,b =10;// Example of initialization
byteB =22;// initializes a byte type variable B.
doublepi =3.14159;// declares and assigns a value of PI.
chara ='a';// the char variable a is initialized with value 'a'
Variable Type –Local Variable
•Itdeclaredinsideofmethods,constructors,orblocks.
•Accessmodifiercannotbeusedforlocalvariable.
•Localvariablesarevisibleonlywithinthemethods.
•Variablecanbeaccessedwhenthemethodiscalled.
Class
{
method
{
declarevariable
}
}
Variable Type –Local Variable
publicclass Dog
{
publicvoid dogAge()
{
intage =0;
age =age +7;
System.out.println(“Dog age is : “ +age);
}
publicstaticvoid main(Stringargs[])
{
Dogdog=newDog();
dog.pupAge();
}
}
Variable Type –Instance Variable
•Itdeclareinsideofaclassbutoutsideofmethods.
•Thisvariablecanbeaccessbyanymethods.
•Bycreatingobjectforaclass,wecanaccessthis
variablefrommainmethods.
Class
{
declarevariable
method
{
//can use var
}
}
Variable Type –Instance Variable
publicclass Dog{
intage;
publicvoid Dog(int i){
age =i;
}
publicvoid display(){
System.out.println(“Dog age is : “ +age);
}
publicstaticvoid main(Stringargs[]){
Dogdog=newDog(30);
dog.display();
}
}
Variable Type –Class / Static Variable
•Variabledeclaredinsideofclassbutoutside
ofmethodswithstatickeyword.
•Staticvariablesarestoredinthestatic
memory.
•Staticvariablescanbeaccessedbystatic
methodsorconstructors.
Class
{
declare staticvariable
constructor
{
//can use var
}
static method
{
//can use var
}
}