Instance Variables vs Static Variables in Java
An instance variable is declared inside a class but outside any method, and every object gets its own independent copy — changing one object's copy never affects another object's copy of that same field. A static variable, marked with the static keyword, belongs to the class itself rather than to any individual object, so there's exactly one shared copy no matter how many objects of that class exist, and every object, and the class itself, sees the same value.
A static variable is a natural fit for data that's genuinely shared across every instance — a running count of how many objects have been created, a shared configuration value, a constant — while an instance variable fits data that's meaningfully different from one object to the next, like each object's own name or balance.
Instance variables
Declared without static, each object gets its own independent copy, initialized fresh for every new instance.
Static variables
Declared with static, exactly one copy exists, shared by the class itself and every one of its instances.
Changing a static variable is visible everywhere
Since there's only one copy, updating it through any single object's reference changes what every other object, and the class, sees too.
Accessing static members
Conventionally through the class name, like ClassName.variable, though accessing through an instance reference also works and means the same thing.
A natural use for static
A running count of created instances, since that value is genuinely about the class as a whole, not about any one object.
public class Counter { static int totalCreated = 0; int id; Counter() { totalCreated++; id = totalCreated; } public static void main(String[] args) { Counter a = new Counter(); Counter b = new Counter(); System.out.println("a's id: " + a.id); System.out.println("b's id: " + b.id); System.out.println("Total created: " + Counter.totalCreated); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.