Instance Variable vs Static Variable

Naveen AnamaneniUpdated · 4 min read

In a cricket team, each player has their own runs scored, but the team has one total score on the board. If you stored the team total inside each player, you'd have eleven different "totals" and none of them right. Fields work the same way: instance variables hold each object's own data, and static variables hold the one value the whole class shares. Choosing the wrong one is a classic bug.

Two Counters

Each object's own count, plus one shared total
Gates.java▶ Try it
public class Gates {
    static class Gate {
        int passed;
        static int totalPassed;
 
        void tap() {
            passed++;
            totalPassed++;
        }
    }
 
    public static void main(String[] args) {
        Gate a = new Gate();
        Gate b = new Gate();
        a.tap(); a.tap(); a.tap();
        b.tap();
        System.out.println("Gate A: " + a.passed);
        System.out.println("Gate B: " + b.passed);
        System.out.println("Station total: " + Gate.totalPassed);
    }
}
Output
Gate A: 3
Gate B: 1
Station total: 4

How it works

  1. Line 3: passed is an instance variable: each gate has its own.
  2. Line 4: totalPassed is a static variable: one value for the class.
  3. Each tap() adds 1 to that gate's passed and 1 to the shared total.

Try it yourself: make passed static too. What do the three lines print now?

Side by Side

Instance variableStatic variable
DeclaredIn the class, without staticIn the class, with static
CopiesOne per objectOne per class
CreatedWhen an object is created with newWhen the class is initialized
DestroyedWhen the object is garbage collectedWhen the class is unloaded (usually at program end)
Lives inThe object, on the heapClass data (method area)
Accessed asobject.fieldClassName.field
Usable from static methodsOnly through an objectYes
Default valueYes (0, false, null)Yes (0, false, null)
Typical useEach account's balance, each ticket's berthA counter, a constant, a shared setting

Constants Are Static Too

Values that never change and are the same for every object should be static final, not instance fields:

Instead ofWrite
final double gstRate = 0.18; in every objectstatic final double GST_RATE = 0.18; once for the class

Common Mistakes

Storing per-object data in a static variable. Every object would overwrite the same value.

Storing a shared counter in an instance variable. Each object would count only itself.

Accessing static variables through objects. a.totalPassed works but hides the fact that it's shared; write Gate.totalPassed.

Interview Corner

What is the difference between an instance variable and a static variable?

An instance variable belongs to an object: each object has its own copy, created with the object. A static variable belongs to the class: there's one copy shared by all objects, created when the class is initialized. Instance variables are accessed through an object; static variables through the class name.

Practice

  1. Easy: In a Student class, decide which should be static: name, rollNo, schoolName, studentCount.
  2. Harder: Write a Ticket class where each ticket gets a unique id (instance) taken from a static nextId counter that starts at 1001.

Quick check: Instance vs static variables

4 questions
1Two objects each change an instance variable. How many values exist?
2Two objects each increase a static counter once from 0. What is its value?
3When is a static variable created?
4Which should be a static variable in a BankAccount class?

Key Takeaways

Was this tutorial helpful?

Lesson 106 of 482