What is the difference between a static member and an instance member in Java, in terms of memory, lifetime and access?
There are three differences, and they are about memory, about how long the thing lives, and about how you reach it.
An instance member belongs to an object. There is one copy of it for every object, each copy has its own place in memory, and it lives exactly as long as the object does. You reach it through an object, either with the dot and a reference, or from inside the object itself with this.
A static member belongs to the class. There is exactly one copy of it for the whole class, no matter how many objects exist, and it lives as long as the class is loaded. You reach it through the class name, and you can reach it without having an object at all.
public class Main {
public static void main(String[] args) {
Counter first = new Counter();
Counter second = new Counter();
first.increment();
first.increment();
second.increment();
System.out.println("first count : " + first.getCount());
System.out.println("second count : " + second.getCount());
System.out.println("total made : " + Counter.getTotalMade());
}
}
class Counter {
private int count; // one copy for every object
private static int totalMade = 0; // one copy for the whole class
public Counter() {
totalMade = totalMade + 1;
}
public void increment() {
this.count = this.count + 1;
}
public int getCount() {
return this.count;
}
public static int getTotalMade() {
return totalMade;
}
}
The output shows the difference clearly. The two counters have their own counts, so one went up to 2 and the other to 1. The total number made is 2, because there is only one copy of that value for the whole class.
There is one more difference that matters for performance. A static member is looked up through the class, and a static method is called without an object, so there is no reference to follow. That is why a utility method that does not need any state is usually static.
The next question in this topic looks at when shared static state is a good idea.