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.
