Difference between class variables and instance variables in Java

Variables are used in Java to store data. There are two types of data variables: Class level variables and Instance level variables.

svg viewer

Instance level variables

An instance variable is individually created for a single object of a class. Suppose that ​there are two objects, object1 and object2, of a single class, ​and both objects have an integer variable named count. If the user changes object1’s count, it will not change object2’s count.

The code below is an example of the phenomena explained above.

class example {
int count; //instance level variable
public static void main(String[] args) {
example obj1 = new example();
example obj2 = new example();
obj1.count=5;
obj2.count=5;
obj1.count++; //change in object1's count
System.out.println(obj1.count);
System.out.println(obj2.count);
}
}

Class level variables

Class variables are shared between all objects. Changing the variable’s data through one object will change the data for all the objects. This is done by using the word static before declaring the data type. The following code explains this.

class example {
static int count; //class level variable
public static void main(String[] args) {
example obj1 = new example();
example obj2 = new example();
obj1.count=5;
obj2.count=5;
obj1.count++; //change in object1's count
System.out.println(obj1.count);
System.out.println(obj2.count);
}
}

As you may have noticed, the same code with the word static changes the implementation. U​pdating object1’s count changes object2’s count as well.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved