Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Instance Variable

An instance variable is a variable that has its separate copy for each object/instance of the class.

Java Programming Language Object and Instance Variable

It is defined in class but outside the method & constructor.

Instance variables are created automatically for every new object creation.

Default values for instance variables vary from type to type. Zero for numeric types, null for reference types and false for boolean types.

Instance variables are accessed by using a reference to object.

For example consider a class named InstanceVar containing a variable var & three objects obj1, obj2 & obj3.

Example I

class InstanceVar 
{
     int var;   // instance variable
	
     public static void main(String args[])
     {
         InstanceVar obj1 = new InstanceVar();
         InstanceVar obj2 = new InstanceVar();
         InstanceVar obj3 = new InstanceVar();
     }
}

Here each instance/object obj1, obj2 & obj3 will contain a separate copy of variable var as shown below:

Java Programming Language Each Object with Separate Copy of Instance Variable

Therefore variable var is known as the instance variable.

Example II

class InstanceVar 
{
     int var = 2;
	
     public static void main(String args[])
     {
         InstanceVar obj1 = new InstanceVar();
         InstanceVar obj2 = new InstanceVar();
         InstanceVar obj3 = new InstanceVar();
         System.out.println("var of obj1 = "+obj1.var);
         System.out.println("var of obj2 = "+obj2.var);
         System.out.println("var of obj3 = "+obj3.var);
     }
}

Output

var of obj1 = 2
var of obj2 = 2
var of obj3 = 2

Before this program, we have stated that objects name of the class InstanceVar are obj1, obj2 & obj3 respectively (for understanding purpose).
But actually, they are not the names but references to objects of InstanceVar type.
And actually, they are represented as shown below:

Java Programming Language Instance Variable Example

Example III

class InstanceVar2 
{
    int var;
	
    public static void main(String args[])
    {
        InstanceVar2 obj1 = new InstanceVar2();
        InstanceVar2 obj2 = new InstanceVar2();
        InstanceVar2 obj3 = new InstanceVar2();
        
        obj1.var = 2;
        obj2.var = 3;
        obj3.var = 4;
         
        System.out.println("var of obj1 = "+obj1.var);
        System.out.println("var of obj2 = "+obj2.var);
        System.out.println("var of obj3 = "+obj3.var);
    }
}

Output

var of obj1 = 2
var of obj2 = 3
var of obj3 = 4

 Java Programming Language Instance Variable Example 2

Note

In Java, we don’t know what does reference contains exactly.
It contains something like an address or a pointer.
But JVM knows how to make use of reference to get the right object.

 

Leave a reply