Bird
Raised Fist0
Javaprogramming~10 mins

Heap memory in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept 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.
Execution 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.
Execution 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
Variable Tracker
VariableStartAfter Step 2After Step 3Final
sundefined"Hello"nullnull
Heap Objectsempty["Hello"]["Hello"]may be freed
Key Moments - 3 Insights
Why does the String object still exist on the heap after s is set to null?
Because setting s to null only removes the reference from the stack; the object remains in heap until garbage collector frees it (see step 3 in execution_table).
What happens to the stack when main method ends?
All stack references are cleared when main ends, so no references remain to heap objects, allowing garbage collection (see step 4).
Is the heap memory freed immediately after setting s to null?
No, garbage collection runs later automatically; the object becomes eligible but is not freed instantly (step 3 vs step 4).
Visual 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
💡 Hint
Check the 'Stack State' column at step 2 in execution_table
At which step does the String object become eligible for garbage collection?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Garbage Collection' column in execution_table
If we never set s to null, what would happen to the String object?
AIt would be immediately garbage collected
BIt would be removed from stack
CIt would remain referenced and not be collected
DIt would cause a compile error
💡 Hint
Refer to variable_tracker and execution_table steps 2 and 3
Concept 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.
Full 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.

Practice

(1/5)
1. Which of the following best describes heap memory in Java?
easy
A. It stores method call information and local variables.
B. It stores primitive variables like int and double.
C. It stores all objects created using new keyword.
D. It stores the Java bytecode instructions.

Solution

  1. Step 1: Understand what heap memory stores

    Heap memory is used to store objects created dynamically using the new keyword in Java.
  2. Step 2: Differentiate from other memory areas

    Primitive variables and method calls are stored on the stack, not heap. Bytecode is stored in method area, not heap.
  3. Final Answer:

    It stores all objects created using new keyword. -> Option C
  4. Quick Check:

    Heap memory = objects from new [OK]
Hint: Heap = objects created with new keyword [OK]
Common Mistakes:
  • Confusing stack with heap memory
  • Thinking primitives are stored in heap
  • Mixing method area with heap
2. Which of the following Java statements correctly creates an object stored in heap memory?
easy
A. String s = new String("hello");
B. int x = 5;
C. double y = 3.14;
D. boolean flag = true;

Solution

  1. Step 1: Identify object creation syntax

    Objects in Java are created using the new keyword, which allocates memory on the heap.
  2. Step 2: Check each option

    String s = new String("hello"); uses new String("hello"), which creates a String object on the heap. Other options declare primitives stored on the stack.
  3. Final Answer:

    String s = new String("hello"); -> Option A
  4. Quick Check:

    Object creation uses new keyword [OK]
Hint: Look for 'new' keyword to spot heap allocation [OK]
Common Mistakes:
  • Assuming primitives use heap
  • Confusing string literals with new String()
  • Ignoring that only new creates heap objects
3. What will be the output of the following Java code?
class Test {
  public static void main(String[] args) {
    String a = new String("abc");
    String b = a;
    a = null;
    System.out.println(b);
  }
}
medium
A. null
B. Runtime exception
C. Compilation error
D. abc

Solution

  1. Step 1: Understand object references and heap

    Variable a points to a String object "abc" in heap. Then b is assigned the same reference.
  2. Step 2: Analyze effect of setting a to null

    Setting a = null removes one reference, but b still points to the object, so it remains accessible.
  3. Step 3: Print b

    Printing b outputs the string "abc".
  4. Final Answer:

    abc -> Option D
  5. Quick Check:

    Reference b still points to "abc" [OK]
Hint: Nulling one reference doesn't delete object if others exist [OK]
Common Mistakes:
  • Assuming object is deleted when one reference is null
  • Confusing references with objects
  • Expecting null output incorrectly
4. Identify the error in the following Java code related to heap memory usage:
public class Demo {
  public static void main(String[] args) {
    int[] arr = new int[5];
    arr = null;
    System.out.println(arr.length);
  }
}
medium
A. No error, prints 5
B. NullPointerException at runtime
C. Compilation error due to null assignment
D. Array size becomes zero

Solution

  1. Step 1: Understand array creation and null assignment

    The array is created on heap with size 5, then arr reference is set to null.
  2. Step 2: Analyze printing arr.length

    Since arr is null, accessing arr.length causes a NullPointerException at runtime.
  3. Final Answer:

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

    Accessing member on null reference throws exception [OK]
Hint: Accessing null reference causes NullPointerException [OK]
Common Mistakes:
  • Thinking null assignment causes compile error
  • Expecting array length to print after null
  • Confusing null with empty array
5. Consider this Java code snippet:
class Node {
  int value;
  Node next;
  Node(int val) { value = val; }
}

public class Test {
  public static void main(String[] args) {
    Node n1 = new Node(1);
    Node n2 = new Node(2);
    n1.next = n2;
    n2.next = n1;
    n1 = null;
    n2 = null;
    // What happens to the Node objects in heap?
  }
}

What happens to the two Node objects in heap after n1 and n2 are set to null?
hard
A. Both objects become unreachable and eligible for garbage collection.
B. Objects remain in heap because they reference each other, preventing garbage collection.
C. Only n1 object is collected, n2 remains.
D. Objects cause a memory leak and crash the program.

Solution

  1. Step 1: Analyze object references after null assignments

    Both n1 and n2 references are set to null, so no external references point to these objects.
  2. Step 2: Understand garbage collection with cyclic references

    Even though the two objects reference each other, Java's garbage collector detects unreachable cycles and frees them.
  3. Final Answer:

    Both objects become unreachable and eligible for garbage collection. -> Option A
  4. Quick Check:

    Unreachable objects, even cyclic, are collected [OK]
Hint: Java GC collects unreachable cyclic objects too [OK]
Common Mistakes:
  • Thinking cyclic references prevent garbage collection
  • Assuming memory leak without external references
  • Confusing references with reachability
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