Bird
Raised Fist0
Javaprogramming~10 mins

Object lifecycle in Java - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Object lifecycle
Object Declaration
Memory Allocation
Constructor Called
Object Ready to Use
Object Usage
Object No Longer Referenced
Garbage Collector Cleans Object
Memory Freed
This flow shows how a Java object is created, used, and then cleaned up by the system when no longer needed.
Execution Sample
Java
class Box {
  Box() {
    System.out.println("Box created");
  }
}

Box b = new Box();
This code creates a Box object, calling its constructor which prints a message.
Execution Table
StepActionEvaluationResult
1Declare variable bb is null (no object yet)b = null
2Allocate memory for new BoxMemory allocated for Box objectMemory reserved
3Call Box constructorConstructor runsPrints 'Box created'
4Assign object reference to bb points to new Box objectb = reference to Box
5Use object bObject can be usedOperations on b possible
6b set to null or goes out of scopeNo references to Box objectObject eligible for garbage collection
7Garbage collector runsObject memory freedMemory reclaimed
💡 Execution stops when object is no longer referenced and garbage collector frees memory.
Variable Tracker
VariableStartAfter Step 1After Step 4After Step 6Final
bundefinednullreference to Box objectnullnull
Key Moments - 3 Insights
Why is the object not immediately deleted after setting b to null?
Because Java uses garbage collection which runs later; setting b to null only removes the reference, making the object eligible for cleanup (see step 6 and 7 in execution_table).
What happens during the constructor call?
The constructor initializes the object and can run code like printing messages (see step 3 in execution_table).
Can the object be used before the constructor finishes?
No, the object is only ready to use after the constructor completes (see step 4 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of variable b after step 1?
Aundefined
Breference to Box object
Cnull
Dmemory allocated
💡 Hint
Check the 'Evaluation' column at step 1 in the execution_table.
At which step does the constructor print 'Box created'?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Result' column in the execution_table for the printing action.
If variable b never goes out of scope or is set to null, what happens to the object?
AIt is immediately garbage collected
BIt remains in memory and usable
CConstructor runs again
DMemory is freed manually
💡 Hint
Refer to step 6 and 7 in execution_table about object eligibility for garbage collection.
Concept Snapshot
Object lifecycle in Java:
1. Declare variable (reference)
2. Allocate memory for object
3. Call constructor to initialize
4. Use object via reference
5. Remove references (null or out of scope)
6. Garbage collector frees memory later
Full Transcript
This visual trace shows the lifecycle of a Java object from declaration to garbage collection. First, a variable is declared and set to null. Then memory is allocated for the object, and the constructor runs, printing a message. The variable is assigned the object reference, making it ready to use. When the variable is set to null or goes out of scope, the object has no references and becomes eligible for garbage collection. Finally, the garbage collector frees the memory. Key points include understanding that the constructor runs before the object is usable, and that garbage collection happens later, not immediately after losing references.

Practice

(1/5)
1. Which statement best describes the lifecycle of an object in Java?
easy
A. Objects must be manually deleted to free memory.
B. An object is created automatically without new and never gets removed.
C. Objects live forever once created.
D. An object is created with new and exists as long as it has references.

Solution

  1. Step 1: Understand object creation

    In Java, objects are created using the new keyword which allocates memory.
  2. 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.
  3. Final Answer:

    An object is created with new and exists as long as it has references. -> Option D
  4. Quick Check:

    Object lifecycle = created with new and referenced [OK]
Hint: Objects live only while referenced, created with new [OK]
Common Mistakes:
  • Thinking objects live forever
  • Believing manual deletion is needed
  • Assuming objects are created without new
2. Which of the following is the correct way to create a new object of class Car in Java?
easy
A. Car myCar = Car();
B. Car myCar = new Car();
C. new Car myCar();
D. Car myCar = create Car();

Solution

  1. Step 1: Recall Java object creation syntax

    In Java, to create an object, use the syntax: ClassName variable = new ClassName();
  2. Step 2: Match options with correct syntax

    Car myCar = new Car(); matches the correct syntax. Other options have syntax errors or invalid keywords.
  3. Final Answer:

    Car myCar = new Car(); -> Option B
  4. Quick Check:

    Use new keyword to create objects [OK]
Hint: Use 'new' keyword with class name and parentheses [OK]
Common Mistakes:
  • Omitting 'new' keyword
  • Incorrect order of keywords
  • Using invalid method-like syntax
3. What will be the output of the following Java code?
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");
        }
    }
}
medium
A. Object is alive
B. Object is gone
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Analyze object references

    Initially, obj1 points to a new Demo object. Then obj2 is assigned the same reference as obj1.
  2. Step 2: Check null assignment and condition

    obj1 is set to null, but obj2 still references the object. The if condition checks obj2 != null, which is true.
  3. Final Answer:

    Object is alive -> Option A
  4. Quick Check:

    Object lives while referenced = true [OK]
Hint: Object lives if any reference points to it [OK]
Common Mistakes:
  • Assuming object is gone when one reference is null
  • Confusing reference variables with objects
  • Expecting compilation or runtime errors
4. Identify the error in the following code related to object lifecycle:
public class Test {
    public static void main(String[] args) {
        String s = new String("hello");
        s = null;
        System.out.println(s.length());
    }
}
medium
A. Compilation error due to null assignment
B. No error, prints length of string
C. NullPointerException at runtime
D. String object is not created

Solution

  1. Step 1: Understand object reference and null assignment

    The variable s initially references a String object. Then it is set to null, so it no longer points to any object.
  2. Step 2: Analyze method call on null reference

    Calling s.length() when s is null causes a NullPointerException at runtime.
  3. Final Answer:

    NullPointerException at runtime -> Option C
  4. Quick Check:

    Calling method on null reference causes exception [OK]
Hint: Don't call methods on null references [OK]
Common Mistakes:
  • Thinking null assignment causes compile error
  • Expecting output instead of exception
  • Ignoring null pointer risks
5. Consider the following code snippet:
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;?
hard
A. Neither a nor b nodes are eligible
B. Only the node originally referenced by b is eligible
C. Both nodes are eligible
D. Only the node referenced by a is eligible

Solution

  1. Step 1: Analyze references after assignment

    Variable a references a Node with value 1. This node's next points to the Node with value 2.
  2. Step 2: Check if nodes are still reachable

    Even though b is set to null, the Node with value 2 is still referenced by a.next. So both nodes are still reachable and not eligible for garbage collection.
  3. Final Answer:

    Neither a nor b nodes are eligible -> Option A
  4. Quick Check:

    Objects reachable via references are not collected [OK]
Hint: Objects reachable from any reference stay alive [OK]
Common Mistakes:
  • Assuming null variable means object is collected
  • Ignoring references inside objects
  • Confusing variable null with object eligibility