Static variables in Java - Time & Space Complexity
Let's explore how using static variables affects the time it takes for a program to run.
We want to see if static variables change how the program's work grows as input grows.
Analyze the time complexity of the following code snippet.
public class Counter {
static int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
This code defines a static variable count shared by all instances, incremented by the increment method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Incrementing the static variable
counteach timeincrement()is called. - How many times: Once per call to
increment(), no loops inside the method.
Each call to increment() does one simple step: add one to count.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments |
| 100 | 100 increments |
| 1000 | 1000 increments |
Pattern observation: The work grows directly with how many times you call increment(). No extra loops or nested work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of increments done.
[X] Wrong: "Static variables make the program faster or slower because they are shared."
[OK] Correct: Static variables just share data across instances but do not change how many steps the program takes to run.
Understanding static variables helps you explain how data is shared in programs and how that affects performance in simple ways.
"What if the increment() method had a loop that ran n times inside it? How would the time complexity change?"
