Object lifetime in Java - Time & Space Complexity
When we talk about object lifetime in Java, we want to understand how long objects stay active during program execution.
We ask: How does the time spent managing objects grow as the program runs?
Analyze the time complexity of the following code snippet.
public class ObjectLifetime {
public void createObjects(int n) {
for (int i = 0; i < n; i++) {
String obj = new String("Object " + i);
System.out.println(obj);
}
}
}
This code creates and prints n String objects one by one inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new String object and printing it inside the loop.
- How many times: Exactly n times, once per loop iteration.
As n grows, the number of objects created and printed grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 objects created and printed |
| 100 | 100 objects created and printed |
| 1000 | 1000 objects created and printed |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to create and print objects grows directly with the number of objects.
[X] Wrong: "Creating objects inside a loop is free or constant time regardless of n."
[OK] Correct: Each object creation takes time, so more objects mean more total time.
Understanding how object creation scales helps you write efficient code and explain resource use clearly.
"What if we reused a single String object instead of creating a new one each time? How would the time complexity change?"
