0
0
Javaprogramming~15 mins

Static variables in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept 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.
code_blocksExecution 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.
data_tableExecution 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
search_insightsVariable Tracker
VariableStartAfter Step 2After Step 3Final
count (static)0122
a (instance)nullobject createdobject createdobject created
b (instance)nullnullobject createdobject created
keyKey Moments - 3 Insights
Why does the static variable 'count' keep the total count across all objects?
If we create more objects, will 'count' reset for each?
Can we access 'count' without creating any objects?
psychologyVisual 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
photo_cameraConcept 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().
contractFull 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.