Object lifecycle in Java - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time to create and destroy objects changes as we make more objects.
How does the program's work grow when handling many objects?
Analyze the time complexity of the following code snippet.
public class ObjectLifecycle {
public static void main(String[] args) {
int n = 1000;
for (int i = 0; i < n; i++) {
MyObject obj = new MyObject();
obj.doWork();
}
}
}
class MyObject {
void doWork() {
// some simple operation
}
}
This code creates n objects one after another and calls a simple method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating an object and calling its method.
- How many times: Exactly n times, once per loop iteration.
Each new object adds a fixed amount of work, so the total work grows steadily as n grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations and method calls |
| 100 | 100 object creations and method calls |
| 1000 | 1000 object creations and method calls |
Pattern observation: The work increases directly in proportion to the number of objects.
Time Complexity: O(n)
This means the time grows in a straight line as you create more objects.
[X] Wrong: "Creating objects is free or constant time regardless of how many are made."
[OK] Correct: Each object creation takes time, so making more objects adds more work.
Understanding how object creation scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if the doWork() method itself contained a loop that ran n times? How would the time complexity change?"
Practice
Solution
Step 1: Understand object creation
In Java, objects are created using thenewkeyword which allocates memory.Step 2: Understand object lifetime
An object remains alive as long as there is at least one reference pointing to it. When no references remain, it becomes eligible for garbage collection.Final Answer:
An object is created withnewand exists as long as it has references. -> Option DQuick Check:
Object lifecycle = created withnewand referenced [OK]
- Thinking objects live forever
- Believing manual deletion is needed
- Assuming objects are created without new
Car in Java?Solution
Step 1: Recall Java object creation syntax
In Java, to create an object, use the syntax:ClassName variable = new ClassName();Step 2: Match options with correct syntax
Car myCar = new Car(); matches the correct syntax. Other options have syntax errors or invalid keywords.Final Answer:
Car myCar = new Car(); -> Option BQuick Check:
Usenewkeyword to create objects [OK]
- Omitting 'new' keyword
- Incorrect order of keywords
- Using invalid method-like syntax
class Demo {
public static void main(String[] args) {
Demo obj1 = new Demo();
Demo obj2 = obj1;
obj1 = null;
if (obj2 != null) {
System.out.println("Object is alive");
} else {
System.out.println("Object is gone");
}
}
}Solution
Step 1: Analyze object references
Initially,obj1points to a new Demo object. Thenobj2is assigned the same reference asobj1.Step 2: Check null assignment and condition
obj1is set to null, butobj2still references the object. The if condition checksobj2 != null, which is true.Final Answer:
Object is alive -> Option AQuick Check:
Object lives while referenced = true [OK]
- Assuming object is gone when one reference is null
- Confusing reference variables with objects
- Expecting compilation or runtime errors
public class Test {
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 it is set to null, so it no longer points to any object.Step 2: Analyze method call on null reference
Callings.length()whensis null causes aNullPointerExceptionat runtime.Final Answer:
NullPointerException at runtime -> Option CQuick Check:
Calling method on null reference causes exception [OK]
- Thinking null assignment causes compile error
- Expecting output instead of exception
- Ignoring null pointer risks
class Node {
Node next;
int value;
Node(int val) { value = val; }
}
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 nodes are eligible for garbage collection here?
}
}Which nodes are eligible for garbage collection after
b = null;?Solution
Step 1: Analyze references after assignment
Variableareferences a Node with value 1. This node'snextpoints to the Node with value 2.Step 2: Check if nodes are still reachable
Even thoughbis set to null, the Node with value 2 is still referenced bya.next. So both nodes are still reachable and not eligible for garbage collection.Final Answer:
Neitheranorbnodes are eligible -> Option AQuick Check:
Objects reachable via references are not collected [OK]
- Assuming null variable means object is collected
- Ignoring references inside objects
- Confusing variable null with object eligibility
