Instance variable in java

Instance variable in java are variable which is declared in a class but outside the methods or constructor.

Instance variable in java

In this section you will learn about Instance variable in java. In java all variable must be declared before they are used. The basic form of variable declaration is :

type identifier = value;

The type is one of the data type in java ,identifier is one of the name of the variable.

Here are the various example to declare variable as below:

int a,b,c;      // declaring three variable of type int a,b and c
double pi=3.14; // declaration with initialization both
int e=2,f,g=0;  // declares three int variables and initializing only two variables
byte s=54;     //initializes s
char k='K';    //initializes char k with value of K

There are three kind of variable in java, they are as follows :

  • Local variable
  • Instance Variable
  • class/static variable

Instance variable :

  • Instance variable are declared in a class but outside method or constructor.
  • Instance variable are created when the object is created with new keyword  and destroyed when the object get destroyed.
  • When the space is allocated for object in heap then a slot for each  instance variable value is created.
  • Instance variable are in scope as long as their object in scope.
  • Instance variable are used by all method of a class unless method is marked as static.
  • Access modifier can be given for instance variable.
  • Instance variable have default values, for integer it is 0, boolean it s false and for object reference it is null.
  • Instance variable can be  accesed directly by calling the variable name inside a class.

Example : A code of program for Instance variable

class Employe {
	public String name; //Instance variable is visible in any class
    private int salary;  //This Instance variable is visible only in current class
	public Employe(String name,int salary)
     {;   //instance varible Name and salary is assigned in constructor
    public void display() // Displaying the values
    	System.out.println("Employee Name = "+name);
        System.out.println("Employee Salary = " + salary);
public class InstanceVariable
	public static void main(String args[])
		Employe e=new Employe("XYZ",1000);

Output : After compiling and executing the above program

Download SourceCode


Share on Google+Share on Google+

Instance variable in java

Posted on: June 8, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Instance variable in java  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image