Tutorials

Java Variables


Java Instance Variable


In java, Objects use instance variable to store their states.

Important points related to instance variable

  • Values stored in instance variables are instance specific and these values cannot be shared among different instances.
  • For instance variable each instantiated object or instance of a class will have separate copy (or value).
  • If you donot assign any value to instance variable then it is assigned a default value. We have shown a chart displaying default value of instance variable for different data type at the end of this page.
  • Instance variable should not be declared static.
  • Instance variable should not be declared inside a method.

Example of Instance variable

Source file: Human.java

package variables;

public class Human {

   public String name;  //instance variable
   public static String belongsTo; //class variable

   //overriding toString()
   public String toString(){
         return name;

        }

}

Source file: InstanceVariable.java

package variables;

public class InstanceVariable {

            public static void main(String[] args) {

                        //assign different value to name(instance variable)of each instance
                        Human male = new Human();
                        male.name = "Rajneesh";

                        Human female = new Human();
                        female.name = "Shweta";

                        System.out.println("Name of male:"+ " " + male); //instance variable h1 : Rajneesh
                        System.out.println("Name of female:"+ " " + female); //instance variable h1 : Shweta

            }

}

If you do not initialize the instance variable, then a default value will be assigned to it during run time.

 

See the chart below to know what is the default value for different data type.

 

Default value of instance variable

Primitive data type

Variable Declaration

Default value

int

public int number;

0

short

public short number;

(short)0

long

public long number;

0L

byte

public byte number;

(byte)0

float

public float number;

0.0f

double

public double number;

0.0d

char

public char number;

u0000

boolean

public boolean number;

false

object

 

null

 

 



Please Share this page
Views : 96