0
0
Javaprogramming~15 mins

Heap memory in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept Flow - Heap memory
Start Program Execution
Allocate Objects on Heap
Store References on Stack
Use Objects via References
Garbage Collector Frees Unused Objects
Program Ends
This flow shows how Java allocates objects in heap memory, stores references on the stack, uses objects, and frees unused objects with garbage collection.
code_blocksExecution Sample
Java
class Demo {
  public static void main(String[] args) {
    String s = new String("Hello");
    s = null;
  }
}
This code creates a String object on the heap and then removes the reference, making it eligible for garbage collection.
data_tableExecution Table
StepActionHeap StateStack StateGarbage Collection
1Start main methodEmptyargs reference createdNo
2Create new String object "Hello"["Hello"]s -> "Hello"No
3Set s = null["Hello"]s -> nullEligible for GC
4End main methodHeap may free "Hello"Stack clearedYes
💡 Program ends, heap objects without references are freed by garbage collector
search_insightsVariable Tracker
VariableStartAfter Step 2After Step 3Final
sundefined"Hello"nullnull
Heap Objectsempty["Hello"]["Hello"]may be freed
keyKey Moments - 3 Insights
Why does the String object still exist on the heap after s is set to null?
What happens to the stack when main method ends?
Is the heap memory freed immediately after setting s to null?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of variable 's' after step 2?
A"Hello"
Bnull
Cundefined
DGarbage collected
photo_cameraConcept Snapshot
Heap memory stores objects created with 'new'.
References to these objects live on the stack.
Objects remain in heap until no references point to them.
Garbage collector frees unreferenced objects automatically.
Setting a reference to null removes one pointer but does not free memory immediately.
contractFull Transcript
In Java, when the program runs, objects created with 'new' are stored in heap memory. Variables like 's' hold references to these objects on the stack. When 's' is assigned a new object, the heap stores that object and 's' points to it. If 's' is set to null, the reference is removed, but the object stays in heap until the garbage collector frees it. When the main method ends, all stack references are cleared, allowing the garbage collector to clean up unused objects. This process helps manage memory automatically without manual freeing.