Finally block in Java - Time & Space Complexity
We want to understand how the use of a finally block affects the time it takes for a program to run.
Specifically, does adding a finally block change how the program's running time grows as input size increases?
Analyze the time complexity of the following code snippet.
public void process(int[] data) {
try {
for (int i = 0; i < data.length; i++) {
System.out.println(data[i]);
}
} finally {
System.out.println("Cleanup done");
}
}
This code prints each item in an array and then always prints a cleanup message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through the array elements to print each one.
- How many times: Exactly once for each element in the array.
- Finally block operation: Runs once after the try block, printing a single message.
The loop runs once per item, so if the array size doubles, the loop runs twice as many times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints + 1 cleanup |
| 100 | 100 prints + 1 cleanup |
| 1000 | 1000 prints + 1 cleanup |
Pattern observation: The number of prints grows with input size, but the cleanup message is always just one print.
Time Complexity: O(n)
This means the running time grows linearly with the number of items; the finally block does not add extra growth.
[X] Wrong: "The finally block runs multiple times and makes the program slower as input grows."
[OK] Correct: The finally block runs only once after the try block, so it does not repeat with input size.
Understanding how finally blocks behave helps you reason about program flow and performance clearly, a useful skill in coding and debugging.
"What if the finally block contained a loop over the same array? How would the time complexity change?"