Static blocks in Java - Time & Space Complexity
Static blocks run once when a class loads, so their time cost matters for startup speed.
We want to know how the time to run static blocks grows as their code size or input changes.
Analyze the time complexity of the following code snippet.
public class Example {
static int[] data = new int[1000];
static {
for (int i = 0; i < data.length; i++) {
data[i] = i * 2;
}
}
}
This code fills an array with values once when the class loads using a static block.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-loop that runs through the array to assign values.
- How many times: Exactly once, but it runs for each element in the array (n times).
As the array size grows, the loop runs more times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The time grows in a straight line as the input size increases.
Time Complexity: O(n)
This means the time to run the static block grows directly with the size of the array it processes.
[X] Wrong: "Static blocks run instantly and don't affect performance."
[OK] Correct: Static blocks run once but can do a lot of work, so their time cost grows with what they do inside.
Understanding static block time helps you explain startup costs and initialization in Java programs clearly and confidently.
"What if the static block called another method that also loops over the array? How would the time complexity change?"
