Java – Static and Instance Variables

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 –

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 –

package com.selftechy.learnjava;

public class MainMethod {

	 * Author - Seetaram Hegde
	public static void main(String[] args) {
		TestCase tc = new TestCase();

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 Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.