Heap memory is where Java stores objects and data created during a program's run. It helps manage memory so your program can use space efficiently.
Heap memory in Java
public class Example { public static void main(String[] args) { // Creating an object stored in heap memory MyObject myObject = new MyObject(); } } class MyObject { int value; // Object fields and methods }
Objects created with new are stored in heap memory.
Primitive variables like int inside methods are stored in stack memory, but objects live in heap.
obj holds a reference to it.MyObject obj = new MyObject();int number = 5;
obj points to nothing, so no heap memory is allocated.MyObject obj = null; // No object created, no heap memory used
This program creates two Person objects stored in heap memory. It shows how references point to objects and how setting a reference to null means the object can be cleaned up by Java's garbage collector.
public class HeapMemoryDemo { public static void main(String[] args) { System.out.println("Start of program"); // Create first object in heap Person personOne = new Person("Alice", 30); System.out.println("Person One: " + personOne); // Create second object in heap Person personTwo = new Person("Bob", 25); System.out.println("Person Two: " + personTwo); // Nullify reference to personOne personOne = null; System.out.println("Person One reference set to null"); System.out.println("End of program"); } } class Person { String name; int age; Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return name + ", age " + age; } }
Time complexity: Creating objects in heap is generally fast but depends on JVM implementation.
Space complexity: Heap size limits how many objects you can create; too many objects can cause OutOfMemoryError.
Common mistake: Confusing stack and heap memory. Variables hold references on stack, but objects live in heap.
Use heap memory for objects that need to live beyond method calls. Use stack for temporary primitive variables.
Heap memory stores all objects created with new in Java.
References to objects live on the stack, but the actual objects live in heap.
Java automatically manages heap memory with garbage collection to free unused objects.
Practice
heap memory in Java?Solution
Step 1: Understand what heap memory stores
Heap memory is used to store objects created dynamically using thenewkeyword in Java.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.Final Answer:
It stores all objects created usingnewkeyword. -> Option CQuick Check:
Heap memory = objects fromnew[OK]
- Confusing stack with heap memory
- Thinking primitives are stored in heap
- Mixing method area with heap
Solution
Step 1: Identify object creation syntax
Objects in Java are created using thenewkeyword, which allocates memory on the heap.Step 2: Check each option
String s = new String("hello"); usesnew String("hello"), which creates a String object on the heap. Other options declare primitives stored on the stack.Final Answer:
String s = new String("hello"); -> Option AQuick Check:
Object creation uses new keyword [OK]
- Assuming primitives use heap
- Confusing string literals with new String()
- Ignoring that only new creates heap objects
class Test {
public static void main(String[] args) {
String a = new String("abc");
String b = a;
a = null;
System.out.println(b);
}
}Solution
Step 1: Understand object references and heap
Variableapoints to a String object "abc" in heap. Thenbis assigned the same reference.Step 2: Analyze effect of setting
Settingato nulla = nullremoves one reference, butbstill points to the object, so it remains accessible.Step 3: Print
Printingbboutputs the string "abc".Final Answer:
abc -> Option DQuick Check:
Reference b still points to "abc" [OK]
- Assuming object is deleted when one reference is null
- Confusing references with objects
- Expecting null output incorrectly
public class Demo {
public static void main(String[] args) {
int[] arr = new int[5];
arr = null;
System.out.println(arr.length);
}
}Solution
Step 1: Understand array creation and null assignment
The array is created on heap with size 5, thenarrreference is set to null.Step 2: Analyze printing
Sincearr.lengtharris null, accessingarr.lengthcauses a NullPointerException at runtime.Final Answer:
NullPointerException at runtime -> Option BQuick Check:
Accessing member on null reference throws exception [OK]
- Thinking null assignment causes compile error
- Expecting array length to print after null
- Confusing null with empty array
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?Solution
Step 1: Analyze object references after null assignments
Bothn1andn2references are set to null, so no external references point to these objects.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.Final Answer:
Both objects become unreachable and eligible for garbage collection. -> Option AQuick Check:
Unreachable objects, even cyclic, are collected [OK]
- Thinking cyclic references prevent garbage collection
- Assuming memory leak without external references
- Confusing references with reachability
Ready to prove it?
Pass the test and this pattern moves unknown
