Bird
Raised Fist0
Javaprogramming~10 mins

Static variables in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Static variables
Class Loaded
↓
Static Variable Created
↓
Objects Created
↓
Objects Share Static Variable
↓
Static Variable Value Changes
↓
All Objects See Updated Value
When a class loads, its static variables are created once and shared by all objects of that class. Changes to static variables affect all instances.
Execution Sample
Java
class Counter {
  static int count = 0;
  Counter() { count++; }
  static int getCount() { return count; }
}

public class Main {
  public static void main(String[] args) {
    Counter a = new Counter();
    Counter b = new Counter();
    System.out.println(Counter.getCount());
  }
}
This code creates two Counter objects, each increments the shared static count, then prints the total count.
Execution Table
StepActionStatic countInstance createdOutput
1Class Counter loaded, static count initialized to 00No
2Create object a, constructor increments count1a
3Create object b, constructor increments count2b
4Call Counter.getCount(), returns static count2a,b2
💡 Program ends after printing static count 2
Variable Tracker
VariableStartAfter Step 2After Step 3Final
count (static)0122
a (instance)nullobject createdobject createdobject created
b (instance)nullnullobject createdobject created
Key Moments - 3 Insights
Why does the static variable 'count' keep the total count across all objects?
Because 'count' is static, it belongs to the class itself, not individual objects. As shown in execution_table steps 2 and 3, each constructor call increments the same shared 'count'.
If we create more objects, will 'count' reset for each?
No, 'count' is initialized once when the class loads (step 1). It keeps increasing with each new object, as seen in steps 2 and 3.
Can we access 'count' without creating any objects?
Yes, because 'count' is static, you can access it via the class name directly, like Counter.getCount(), without any object.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' after creating object b (step 3)?
A1
B2
C0
D3
💡 Hint
Check the 'Static count' column at step 3 in the execution_table.
At which step does the static variable 'count' get initialized?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the first row in execution_table where 'count' is set to 0.
If we add a third object creation after step 3, what will be the output of getCount()?
A2
B1
C3
D0
💡 Hint
Each new object increments 'count' by 1 as shown in steps 2 and 3.
Concept Snapshot
Static variables belong to the class, not instances.
They are created once when the class loads.
All objects share the same static variable.
Changes to static variables affect all instances.
Access static variables via ClassName.variable or ClassName.method().
Full Transcript
Static variables in Java are variables that belong to the class itself, not to any individual object. When the class loads, the static variables are created once and shared by all objects. For example, in the code, the static variable 'count' starts at 0. Each time a new Counter object is created, the constructor increases 'count' by 1. This means all objects see the same 'count' value. After creating two objects, 'count' becomes 2. You can access static variables directly from the class without creating objects. This sharing behavior is useful for keeping track of data common to all instances, like counting how many objects have been made.

Practice

(1/5)
1. What is a key characteristic of a static variable in Java?
easy
A. It belongs to the class and is shared by all instances.
B. It is unique to each object created from the class.
C. It can only be accessed inside instance methods.
D. It is automatically deleted when an object is destroyed.

Solution

  1. Step 1: Understand static variable ownership

    A static variable belongs to the class itself, not to any individual object.
  2. Step 2: Recognize sharing behavior

    Because it belongs to the class, all objects share the same static variable value.
  3. Final Answer:

    It belongs to the class and is shared by all instances. -> Option A
  4. Quick Check:

    Static variable = shared by all objects [OK]
Hint: Static means shared by class, not per object [OK]
Common Mistakes:
  • Thinking static variables are unique per object
  • Confusing static with instance variables
  • Assuming static variables are deleted with objects
2. Which of the following is the correct way to declare a static variable in Java?
easy
A. static int count;
B. int static count;
C. int count static;
D. count static int;

Solution

  1. Step 1: Recall Java syntax for static variables

    The keyword static comes before the type when declaring a static variable.
  2. Step 2: Check each option

    Only static int count; follows the correct syntax.
  3. Final Answer:

    static int count; -> Option A
  4. Quick Check:

    static keyword before type = correct syntax [OK]
Hint: Put 'static' before the type when declaring [OK]
Common Mistakes:
  • Placing static after the variable name
  • Mixing order of keywords
  • Using invalid syntax order
3. What will be the output of the following Java code?
class Test {
    static int count = 0;
    Test() {
        count++;
    }
    public static void main(String[] args) {
        new Test();
        new Test();
        System.out.println(Test.count);
    }
}
medium
A. Compilation error
B. 1
C. 0
D. 2

Solution

  1. Step 1: Understand static variable incrementation

    Each time a new Test object is created, the constructor increments count by 1.
  2. Step 2: Count the number of objects created

    Two objects are created, so count becomes 2.
  3. Final Answer:

    2 -> Option D
  4. Quick Check:

    Two objects increment count twice = 2 [OK]
Hint: Static count increments with each new object [OK]
Common Mistakes:
  • Assuming count resets for each object
  • Confusing instance and static variables
  • Expecting compilation error due to static usage
4. Identify the error in the following code snippet:
class Counter {
    static int count;
    void increment() {
        count++;
    }
    public static void main(String[] args) {
        Counter c = new Counter();
        c.increment();
        System.out.println(count);
    }
}
medium
A. Cannot access static variable from instance method.
B. No error; code runs and prints 1.
C. Cannot access static variable directly in static method without class name.
D. Static variable count is not initialized.

Solution

  1. Step 1: Check static variable initialization

    Static int variables default to 0 if not explicitly initialized.
  2. Step 2: Verify method calls and access

    The instance method increment() correctly increments the static variable. The static method main accesses count directly, which is allowed.
  3. Final Answer:

    No error; code runs and prints 1. -> Option B
  4. Quick Check:

    Static variable accessible and increments correctly [OK]
Hint: Static vars default to 0; accessible in static main [OK]
Common Mistakes:
  • Thinking static vars must be explicitly initialized
  • Assuming static vars can't be accessed without class name inside same class
  • Confusing instance and static method access rules
5. Consider this Java class:
class Employee {
    static int employeeCount = 0;
    String name;
    Employee(String name) {
        this.name = name;
        employeeCount++;
    }
    static void printCount() {
        System.out.println("Total employees: " + employeeCount);
    }
}

public class Main {
    public static void main(String[] args) {
        Employee e1 = new Employee("Alice");
        Employee e2 = new Employee("Bob");
        e1.printCount();
        Employee.printCount();
    }
}

What will be the output when running Main?
hard
A. Total employees: 1 Total employees: 2
B. Total employees: 2 Total employees: 1
C. Total employees: 2 Total employees: 2
D. Compilation error due to calling static method on instance

Solution

  1. Step 1: Count employees created

    Two Employee objects are created, so employeeCount becomes 2.
  2. Step 2: Understand static method calls

    Calling printCount() on instance e1 or class Employee both print the same static variable value.
  3. Final Answer:

    Total employees: 2 Total employees: 2 -> Option C
  4. Quick Check:

    Static method prints shared count = 2 [OK]
Hint: Static method prints shared count; instance call allowed [OK]
Common Mistakes:
  • Thinking static method can't be called on instance
  • Assuming employeeCount resets per object
  • Confusing output order or values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard