0
0
Javaprogramming~15 mins

Garbage collection overview in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept Flow - Garbage collection overview
Start Program
Create Objects
Objects Used?
NoMark for Garbage Collection
Remove Unused Objects
Continue Using Objects
Free Memory
Program Ends
This flow shows how Java creates objects, checks if they are still used, and if not, marks and removes them to free memory.
code_blocksExecution Sample
Java
public class Demo {
  public static void main(String[] args) {
    Object obj = new Object();
    obj = null;
    System.gc();
  }
}
This code creates an object, removes its reference, and requests garbage collection.
data_tableExecution Table
StepActionObject ReferenceGarbage Collection StatusMemory Status
1Create new Objectobj -> Object1Not markedMemory allocated for Object1
2Set obj to nullobj -> nullObject1 becomes unreachableMemory still allocated
3Call System.gc()obj -> nullGarbage collector runsMemory freed for Object1
4Program endsobj -> nullNo more objectsMemory clean
💡 Program ends, all unreachable objects are collected and memory is freed
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
objnullObject1 referencenullnullnull
keyKey Moments - 2 Insights
Why does setting obj to null make the object eligible for garbage collection?
Does calling System.gc() guarantee immediate garbage collection?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the status of the object reference?
Aobj is set to null
Bobj points to a new object
Cobj still points to the object
Dobj is undefined
photo_cameraConcept Snapshot
Garbage Collection in Java:
- Objects created use memory.
- When no references point to an object, it becomes unreachable.
- Unreachable objects are marked for garbage collection.
- JVM frees memory by removing unreachable objects.
- System.gc() suggests JVM to run GC but does not guarantee immediate action.
contractFull Transcript
This visual execution shows how Java manages memory with garbage collection. First, an object is created and referenced by a variable. When the variable is set to null, the object has no references and becomes unreachable. The garbage collector then marks this object and frees its memory when System.gc() is called. This process helps keep memory clean and prevents leaks by removing objects no longer in use.