Bird
Raised Fist0
Javaprogramming~10 mins

Object lifetime in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Object lifetime
Create Object with new
↓
Object exists in heap
↓
Reference variable points to object
↓
Use object via reference
↓
Reference set to null or goes out of scope
↓
No references to object
↓
Garbage Collector removes object
↓
Memory freed
This flow shows how an object is created, used, and then removed when no references point to it.
Execution Sample
Java
public class Demo {
    public static void main(String[] args) {
        String s = new String("Hello");
        s = null;
    }
}
This code creates a String object, then removes the reference, making the object eligible for garbage collection.
Execution Table
StepActionReference Variable 's'Object in HeapGarbage Collection Eligible
1Create new String objectPoints to new String("Hello")String("Hello") createdNo
2Assign null to snullString("Hello") still existsYes
3End of main methodnullString("Hello") still existsYes
💡 Program ends, object without references is eligible for garbage collection.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
sundefinedpoints to String("Hello")nullnull
Key Moments - 3 Insights
Why does the object still exist after setting the reference to null?
Because the object is in the heap memory and only removed by garbage collection, which happens after no references point to it, as shown in execution_table step 2.
Does setting the reference to null immediately delete the object?
No, setting the reference to null only removes the pointer; the object remains until garbage collector removes it, as seen in execution_table step 3.
What happens if there are multiple references to the same object?
The object stays alive until all references are removed or set to null, meaning garbage collection only happens when no references remain.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 's' after step 1?
Aundefined
Bnull
Cpoints to String("Hello")
DGarbage collected
💡 Hint
Check the 'Reference Variable s' column in execution_table row for step 1.
At which step does the object become eligible for garbage collection?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Garbage Collection Eligible' column in execution_table.
If we had another reference to the object, when would it become eligible for garbage collection?
AAfter all references are null or out of scope
BImmediately after creation
CBefore setting any reference to null
DNever
💡 Hint
Refer to key_moments explanation about multiple references.
Concept Snapshot
Object lifetime in Java:
- Objects created with 'new' live in heap memory.
- Reference variables point to objects.
- When references are set to null or go out of scope, objects become unreachable.
- Garbage Collector removes unreachable objects to free memory.
- Object removal timing is managed by JVM, not immediate on null assignment.
Full Transcript
In Java, when you create an object using 'new', it is stored in heap memory. A reference variable points to this object. You can use the object through this reference. When you set the reference to null or it goes out of scope, the object no longer has any references pointing to it. At this point, the object becomes eligible for garbage collection. The Java Garbage Collector will then remove the object from memory to free space. This process is automatic and happens sometime after the object becomes unreachable, not immediately when the reference is set to null.

Practice

(1/5)
1. Which statement best describes the lifetime of an object in Java?
easy
A. An object exists as long as there is at least one reference to it.
B. An object exists only during the execution of the main method.
C. An object is deleted immediately after it is created.
D. An object exists forever once created, regardless of references.

Solution

  1. Step 1: Understand object references in Java

    Objects are created using new and remain in memory while referenced.
  2. Step 2: Recognize garbage collection behavior

    When no references point to an object, Java's garbage collector can remove it.
  3. Final Answer:

    An object exists as long as there is at least one reference to it. -> Option A
  4. Quick Check:

    Object lifetime depends on references [OK]
Hint: Remember: objects live while referenced, else garbage collected [OK]
Common Mistakes:
  • Thinking objects exist only during main method
  • Believing objects are deleted immediately after creation
  • Assuming objects live forever regardless of references
2. Which of the following is the correct way to create a new object in Java?
easy
A. MyClass obj = MyClass();
B. MyClass obj = create MyClass();
C. MyClass obj = new MyClass();
D. MyClass obj = new MyClass;

Solution

  1. Step 1: Recall Java object creation syntax

    Objects are created using the new keyword followed by the constructor call with parentheses.
  2. 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 missing new, wrong keywords, or missing parentheses.
  3. Final Answer:

    MyClass obj = new MyClass(); -> Option C
  4. Quick Check:

    Use new ClassName() to create objects [OK]
Hint: Use 'new' keyword plus parentheses to create objects [OK]
Common Mistakes:
  • Omitting the 'new' keyword
  • Forgetting parentheses after class name
  • Using incorrect keywords like 'create'
3. What will be the output of the following code?
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");
    }
  }
}
medium
A. Runtime exception
B. Object dead
C. Compilation error
D. Object alive

Solution

  1. Step 1: Analyze object references

    Initially, obj1 points to the new object. Then obj2 also points to the same object.
  2. Step 2: Check effect of setting obj1 to null

    Setting obj1 to null removes one reference, but obj2 still references the object, so it remains alive.
  3. Final Answer:

    Object alive -> Option D
  4. Quick Check:

    Object lives while any reference exists [OK]
Hint: Object stays alive if any reference points to it [OK]
Common Mistakes:
  • Assuming object is dead after one reference is null
  • Confusing references with object existence
  • Expecting compilation or runtime errors
4. Identify the error in the following code related to object lifetime:
public class Demo {
  public static void main(String[] args) {
    String s = new String("Hello");
    s = null;
    System.out.println(s.length());
  }
}
medium
A. Compilation error due to missing import
B. NullPointerException at runtime
C. No error, prints length of string
D. Syntax error in object creation

Solution

  1. Step 1: Understand object reference and null assignment

    The variable s initially references a String object, then is set to null, removing the reference.
  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 B
  4. Quick Check:

    Calling methods on null causes NullPointerException [OK]
Hint: Never call methods on null references [OK]
Common Mistakes:
  • Thinking code compiles but runs fine
  • Expecting compilation errors instead of runtime
  • Ignoring null assignment effect
5. Consider the following code snippet:
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;?
hard
A. No objects are eligible because a still references b through next.
B. Only object b is eligible because b reference is null.
C. Both a and b objects are eligible for garbage collection.
D. Only object a is eligible because b is null.

Solution

  1. Step 1: Analyze references to objects

    Variable a references the first Node object. Its next field references the second Node object originally referenced by b.
  2. Step 2: Understand effect of setting b to null

    Setting b to null removes one reference to the second Node, but a.next still references it, so it is not eligible for garbage collection.
  3. Final Answer:

    No objects are eligible because a still references b through next. -> Option A
  4. Quick Check:

    Objects live while any reference exists [OK]
Hint: Check all references, including fields, before assuming garbage collection [OK]
Common Mistakes:
  • Assuming null variable means object is collectible
  • Ignoring references inside other objects
  • Confusing variable nullification with object lifetime
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard