Variables (Part-1)
TYPES OF VARIABLES
BASED ON TYPE OF VALUE REPRESENTED
Primitive variable.
Reference variable
BASED ON POSITION OF DECLARATION AND BEHAVIOR
Instance variable
Static variable
Local variable
Based on type of value represented by a variable:
Primitive Variables: used to represent primitive values:
Ex int x = 10;
Reference Variables: used to refer object.
Ex: Student s = new Student();
Based on position of declaration and behavior:Instance Variable: If the value of a variable is varied from object to object. Such type of variables are called instance variable
For every object a separated copy of instance will be created.
WHERE TO DECLARE INSTANCE VARIABLE:
Instance variable should be declare within the class directly but outside of any method, block or constructor.
Instance variable should be declare within the class directly but outside of any method, block or constructor.
WHEN INSTANCE VARIABLE WILL BE CREATED:
At the time of object creation & destroyed at the time of object destruction. Hence the scope of instance variable is exactly same as the scope of object.
WHERE INSTANCE VARIABLE WILL BE STORED :
In the heap memory, as the part of object.
HOW TO ACCESS INSTANCE VARIABLE:
We can't access instance variable directly from static area. but we can access by using object reference.
But we can access instance variable directly from instance area.
class Test{
int x = 10;
public static void min(String[] args){
System.out.println(x); //CE: non-static member can't be accessed directly from static area.
test t = new Test();
System.out.println(t.x); 10
}
public void m(){
System.out.println(x); 10
}
}
For instance variable JVM will always provide default values and we are not required to perform initialization explicitly.
class Test{
class Test{
int x ;
string s ;
double d ;
public static void min(String[] args){
System.out.println(x); //CE: non-static member can't be accessed directly from static area.
test t = new Test();
System.out.println(t.x); 0
System.out.println(t.s); null
System.out.println(t.d); 0.0
}
}
Instance variable also known as object level variable or attributes.

Comments
Post a Comment