0
0
Javaprogramming~15 mins

Object lifetime in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept 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.
code_blocksExecution 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.
data_tableExecution 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.
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2Final
sundefinedpoints to String("Hello")nullnull
keyKey Moments - 3 Insights
Why does the object still exist after setting the reference to null?
Does setting the reference to null immediately delete the object?
What happens if there are multiple references to the same object?
psychologyVisual 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
photo_cameraConcept 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.
contractFull 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.