Java – Static and Instance Variables

by seetaram on July 2, 2011

Object Oriented Programming has a concept of instance variables.  This type of variable is declared in a class and whenever an object is created of that class, a copy of the variable is created.  Instance variable is accessed as “object.variable”

Static variable is also declared in a class but is created only once and used as “class.variable” across the java programs.

Create class – TestCase.java

package com.selftechy.learnjava;

public class TestCase {
	public static int tcCount;
	public int stepcount;

	public int getStepCount(){
		return stepcount;
	}
}

In the above class we have declared two variables – tcCount and stepcount; first one is a static variable (declared using static keyword) and the latter is an instance variable.

Create class – MainMethod.java

package com.selftechy.learnjava;

public class MainMethod {

	/**
	 * Author - Seetaram Hegde
	 */
	public static void main(String[] args) {
		TestCase tc = new TestCase();
		TestCase.tcCount=10;
		tc.stepcount=10;
	}
}

Here, in the above code snippet we can clearly make the difference while accessing these two variables tcCount & stepcount.  tcCount variable is accessed as “TestCase.tcCount” (classname.variable) whereas the second variable (instance variable) is accessed by creating the object (TestCase tc = new TestCase() – tc.stepcount).  Instance variable cannot be accessed without creating the object of the class.

If you want to have some variables which you do not want to create object to access then go for static variables.  Otherwise, go for instance variables.  One more thing to note here is with instance variable you can have different values associated with the variable for each object created for that class.

Leave a Comment

Previous post:

Next post:

Do you want to get updates on the recent articles written? Please subscribe to RSS feed or Email