by Dinesh Thakur Category: Data Type

1. When the variable is declared outside the method, block, and constructor without using any modifier then it is treated as instance variable.
2. If the instance variable is not initialized then it takes the default value of the data type when the object is constructed.
3. Instance variable can use any access specifier.
4. It is accessed within the static method through the object of the class and within the non-static method and constructor directly without creating any object within the class, but outside the class non-static method and constructor invoke instance variable through objects.
5. Instance variable is also known as object level variable as for every instance the value of instance variable is newly initialized.

Here is the Java Example for the program Instance Variable in Java Example:

public class InstanceVariableInJavaExample

{
         int i ; //Instance variable. we can use any access specifier.
         void show()
         {
             i++; //within non-static method it is directly accessed.
         }
         public InstanceVariableInJavaExample()
         {
            i+=2; // within constructor it is directly accessed.
         }
        static void display()
        {
 InstanceVariableInJavaExample InsVar=new InstanceVariableInJavaExample ();
       InsVar.i++; //within static method it is accessed through obj.
       System.out.println(InsVar.i);
       }
      public static void main(String args[])
     {
InstanceVariableInJavaExample InsVar = new InstanceVariableInJavaExample();
     InsVar.show() ;
     InstanceVariableInJavaExample.display();
    }
}

        Instance Variable in Java Example



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.