SrcForge

Lesson 59

Stack Memory vs Heap Memory

In Java, memory management is handled automatically by the JVM, and memory is mainly divided into stack memory and heap memory. Stack memory stores method calls, local variables, and references, while heap memory stores objects and class-level data created during program execution.

Java Track

Save progress as you learn.

61 lessons

Lesson content

In Java, memory management is handled automatically by the JVM, and memory is mainly divided into stack memory and heap memory. Stack memory stores method calls, local variables, and references, while heap memory stores objects and class-level data created during program execution.

What is Memory Management in Java?

Java memory management is the process of allocating and releasing memory for a Java program. The Java Virtual Machine (JVM) manages memory automatically and divides it into two important areas: Stack Memory and Heap Memory. Both are essential, but they are used for different purposes.

Java Memory Areas at a Glance

Stack Memory

Stack memory is mainly used to store:

  • Method calls
  • Local variables
  • Reference variables
  • Partial results during execution

Heap Memory

Heap memory is mainly used to store:

  • Objects
  • Instance data
  • JRE class objects
  • Dynamically allocated memory used by the application

Key Terms

  • Stack memory: The memory area used to store method calls, local variables, and references for each thread.
  • Heap memory: The memory area used to store objects and dynamically allocated data shared across the application.
  • JVM: Java Virtual Machine, the runtime environment that manages Java program execution and memory.
  • Local variable: A variable declared inside a method, constructor, or block.
  • Object reference: A variable that stores the memory address reference of an object.
  • LIFO: Last In, First Out — the order followed by stack memory.

What is Stack Memory in Java?

Stack memory is the memory allocated to each thread at runtime. It is created when a thread starts and is used to store execution-related data.

Stack Memory Stores

  • Method execution order
  • Local variables
  • Primitive values declared inside methods
  • References to objects
  • Temporary calculation results

Important Features of Stack Memory

  • It follows LIFO (Last-In-First-Out) order.
  • Each thread gets its own stack.
  • Memory is automatically removed when a method finishes.
  • It is fast for allocation and deallocation.
  • It is thread-safe because each thread has a separate stack.

Stack Memory Error

If the stack memory exceeds its limit, Java throws:

java.lang.StackOverflowError

What is Heap Memory in Java?

Heap memory is the runtime memory area used to store objects and class-level data. It is created when the JVM starts and is shared by all threads.

Heap Memory Stores

  • Objects created using new
  • Instance variables
  • Arrays
  • JRE class objects
  • Dynamic application data

Important Features of Heap Memory

  • It does not follow LIFO.
  • It is shared by all threads.
  • Memory allocation is dynamic.
  • Objects stay in heap until they are no longer referenced and garbage collected.
  • It is larger than stack memory.

Heap Memory Error

If the JVM cannot allocate more heap space, Java throws:

java.lang.OutOfMemoryError

How Stack and Heap Work Together

When you create an object in Java, the object itself is stored in heap memory, and the reference variable pointing to that object is usually stored in stack memory if it is a local variable.

Example

class Student {
    String name = "Ravi";
}

public class MemoryExample {
    public static void main(String[] args) {
        Student s = new Student();
    }
}

In This Example

  • s is a reference variable stored in stack memory
  • new Student() creates the Student object in heap memory
  • name belongs to the object, so it is part of heap memory

Java Stack Memory vs Heap Memory

Difference Between Stack and Heap in Java

ParameterStack MemoryHeap Memory
PurposeStores method calls, local variables, and object referencesStores objects and JRE classes
OrderFollows LIFO orderNo fixed order
Allocation styleMemory allocation is continuousMemory allocation is dynamic and random
Thread behaviorSeparate stack for each threadShared by all threads
SpeedFaster access and deallocationSlower than stack
SizeSmaller in sizeLarger in size
VisibilityVisible only to the owner threadVisible to all threads
FlexibilityLess flexibleMore flexible
Thread safetyThread-safeNot inherently thread-safe
Object storageStores references to objectsStores actual objects
Memory releaseReleased when method execution endsReleased by garbage collection
Error thrownStackOverflowErrorOutOfMemoryError
JVM option-Xss-Xms, -Xmx

Stack Memory in Detail

1. Created per Thread

Whenever a new thread is created, the JVM creates a separate stack for that thread.

2. Stores Method Frames

Every method call creates a new frame in the stack.

3. Automatically Cleaned Up

When a method returns, its stack frame is removed automatically.

4. Faster Performance

Stack operations are usually faster than heap operations because memory management is simpler.

Heap Memory in Detail

1. Shared Memory Area

Heap is common for all threads in the application.

2. Stores All Objects

Every object created with new is stored in heap memory.

3. Managed by Garbage Collector

Unused objects are removed by Java's Garbage Collector (GC).

4. Suitable for Dynamic Memory Allocation

Heap is used when data needs to live longer than a single method call.

JVM Options for Stack and Heap Memory

Java provides JVM options to configure memory sizes.

Stack Size Option

-Xss

Used to increase stack memory size.

Heap Size Options

-Xms
-Xmx
  • -Xms sets the initial heap size
  • -Xmx sets the maximum heap size

Common Errors Related to Java Memory

StackOverflowError

Occurs when too many method calls are placed on the stack, often due to deep or infinite recursion.

Example reason: A recursive method calling itself without a stopping condition.

OutOfMemoryError

Occurs when heap memory is full and the JVM cannot create new objects.

Example reason: Creating too many objects without releasing references.

Simple Real-World Analogy

Think of Java memory like this: Stack memory is your working desk — it holds the current tasks, quick notes, and temporary items you are actively using. Heap memory is the storage room — it holds larger items and objects that may be needed throughout the program.

Key Takeaways

Stack Memory

  • Stores method calls, local variables, and references
  • Thread-specific
  • Fast and limited in size
  • Uses LIFO

Heap Memory

  • Stores objects and shared runtime data
  • Shared across threads
  • Larger and dynamically managed
  • Managed by garbage collection

FAQ

1. What is the main difference between stack and heap memory in Java?

Stack memory stores method calls, local variables, and references, while heap memory stores objects and dynamically allocated data.

2. Where are Java objects stored?

Java objects are stored in heap memory, while references to those objects may be stored in stack memory if they are local variables.

3. Which error is related to stack memory and heap memory?

Stack memory issues usually cause StackOverflowError, while heap memory issues usually cause OutOfMemoryError.

Stack memory stores method calls, local variables, and references; heap memory stores objects and class-level data.
Stack memory follows LIFO order and is created per thread; heap memory is shared across all threads.
Stack memory is faster and automatically cleaned up when a method returns.
Heap memory is managed by the Garbage Collector and persists until objects are no longer referenced.
Exceeding stack memory throws StackOverflowError; exhausting heap memory throws OutOfMemoryError.
JVM options -Xss configures stack size, while -Xms and -Xmx configure initial and maximum heap size.

Where Java is used

Java in real-world development

Stack Memory

Thread-specific memory area that stores method calls, local variables, and object references using LIFO order.

Heap Memory

Shared memory area used to store objects, instance data, and dynamically allocated application data.

StackOverflowError

Error thrown when stack memory exceeds its limit, often due to deep or infinite recursion.

OutOfMemoryError

Error thrown when the JVM cannot allocate more heap space for new objects.

Garbage Collector

JVM component that removes unused objects from heap memory to free up space.

JVM Memory Options

-Xss configures stack size; -Xms and -Xmx configure the initial and maximum heap size.