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?"
Practice
Solution
Step 1: Understand object references in Java
Objects are created usingnewand remain in memory while referenced.Step 2: Recognize garbage collection behavior
When no references point to an object, Java's garbage collector can remove it.Final Answer:
An object exists as long as there is at least one reference to it. -> Option AQuick Check:
Object lifetime depends on references [OK]
- Thinking objects exist only during main method
- Believing objects are deleted immediately after creation
- Assuming objects live forever regardless of references
Solution
Step 1: Recall Java object creation syntax
Objects are created using thenewkeyword followed by the constructor call with parentheses.Step 2: Check each option's syntax
MyClass obj = new MyClass(); uses correct syntax:new MyClass();. Options A, C, and D are incorrect due to missingnew, wrong keywords, or missing parentheses.Final Answer:
MyClass obj = new MyClass(); -> Option CQuick Check:
Usenew ClassName()to create objects [OK]
- Omitting the 'new' keyword
- Forgetting parentheses after class name
- Using incorrect keywords like 'create'
class Test {
public static void main(String[] args) {
Test obj1 = new Test();
Test obj2 = obj1;
obj1 = null;
if (obj2 != null) {
System.out.println("Object alive");
} else {
System.out.println("Object dead");
}
}
}Solution
Step 1: Analyze object references
Initially,obj1points to the new object. Thenobj2also points to the same object.Step 2: Check effect of setting
Settingobj1to nullobj1to null removes one reference, butobj2still references the object, so it remains alive.Final Answer:
Object alive -> Option DQuick Check:
Object lives while any reference exists [OK]
- Assuming object is dead after one reference is null
- Confusing references with object existence
- Expecting compilation or runtime errors
public class Demo {
public static void main(String[] args) {
String s = new String("Hello");
s = null;
System.out.println(s.length());
}
}Solution
Step 1: Understand object reference and null assignment
The variablesinitially references a String object, then is set tonull, removing the reference.Step 2: Analyze method call on null reference
Callings.length()whensisnullcauses aNullPointerExceptionat runtime.Final Answer:
NullPointerException at runtime -> Option BQuick Check:
Calling methods on null causes NullPointerException [OK]
- Thinking code compiles but runs fine
- Expecting compilation errors instead of runtime
- Ignoring null assignment effect
class Node {
Node next;
int value;
Node(int v) { value = v; }
}
public class Test {
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
a.next = b;
b = null;
// Which objects are eligible for garbage collection here?
}
}Which objects are eligible for garbage collection after setting
b = null;?Solution
Step 1: Analyze references to objects
Variableareferences the first Node object. Itsnextfield references the second Node object originally referenced byb.Step 2: Understand effect of setting
Settingbto nullbto null removes one reference to the second Node, buta.nextstill references it, so it is not eligible for garbage collection.Final Answer:
No objects are eligible becauseastill referencesbthroughnext. -> Option AQuick Check:
Objects live while any reference exists [OK]
- Assuming null variable means object is collectible
- Ignoring references inside other objects
- Confusing variable nullification with object lifetime
Ready to prove it?
Pass the test and this pattern moves unknown
