"KEEP LEARNING, DON'T STOP."
"KEEP LEARNING, DON'T STOP."
In java a variable is nothing but name, which can be used to store the values. A variable is like a container which can hold the different type contents. Internally a variable is represented as a memory location name.
Based on the value holding a variable are divide into two types.
Primitive Variables only allow to store single value and hold single value.
//primitve variable.. int a = 10; char ch = 'b'; float a = 2.5f;
Reference Variable allow to store multiple values in a single variable.
//reference variable.. String str = new String(); String st = new String();
Based on the position of declaration and based on the position all variables divide in three types.
If the value of the variable has to be different from one object to another object then we should go instance variable.
As these variables are created and available with the object that's why these variable are called instance variable or object variable.
Instance variable directly declared inside the class not inside the method area or constructor.
Instance variable allocate the memory when we declare or create the object. Memory will be allocated for these variable inside the object and object created in heap area.
Initialization of instance variable is optional. If we don't initialized instance variable then JVM will automatically assign default value.
Scope and Lifetime of instance variable same as a object. If object gone then instance variable will destroy.
If the value of variable has to be same from one object to another object.
Static Variable are declared directly within the class but using static modifier. But not inside any method or block or constructor.
int i; \\instance variable static int i; \\static variable
Memory will be allocated for these variables at the time of loading the class.
When class is loaded, variable created.
When class is unloaded, variable destroy.
If the requirement for the programmer is to use the same variable for temporary usage then should go for local variable.
These variable created inside the stack memory. Which is temporary memory.
class Book { void pen() { //local varialbe initialization.. String color = "red"; } }
These variable are declared within the method or a block or a constructor, but inside the class.
Memory will we allocated for these variable when method or a block execution starts.
Initialization of local variable is mandatory.
The Scope and Lifetime of local variable is within the method or block. Lifetime of local variable is same as method or block.