--- title: Stack and Heap Memory in Java - Scaler Topics description: Stack and Heap memory are allocated to a program by the Java Virtual Machine (JVM).In this article by Scaler Topics, we will be diving deep into the stack and heap memory. author: Ganesh Kumar Marimuthu category: Java --- ## Overview In Java, Stack and Heap memory are crucial aspects the Java Virtual Machine (JVM) allocates. This article delves into their roles and functionalities. **Stack Memory** employs a Static Memory Allocation Scheme, storing function calls, method-specific primitive data, and object references. Access is in the Last-In-First-Out (LIFO) order. **Heap Memory** facilitates Dynamic Memory Allocation for Java objects and JRE classes during program execution. Objects in the heap have global access, available from any part of the application. ## Stack Allocation in Java The Stack Memory utilizes Static Memory Allocation, storing function calls, method-specific data, and object references. It has a fixed size that doesn't change during execution. The stack memory, a segment in the RAM, is dynamically allocated to each thread during runtime. This allocation occurs upon thread creation, following a Last-In-First-Out (LIFO) order due to its global accessibility. The lifespan of the memory allocated to the stack is confined to the duration of the function, and it ceases to exist once the function concludes. ### Example: Consider a Java program with methods `main`, `addOne`, and `addTwo`. The stack usage is explained step by step. ```java // Java code snippet public class StackMemoryExample { public static void main(String[] args) { int a = 5; int b = 10; // Calling a method that involves stack memory int sum = addNumbers(a, b); System.out.println("Sum: " + sum); } // A method that uses stack memory public static int addNumbers(int x, int y) { // Local variables a and b are stored in stack memory int result = x + y; return result; } } ``` **Output:** ``` Sum: 15 ``` **Explanation:** The main method starts executing, and local variables a and b are stored in the stack memory. The addNumbers method is called, and local variables x, y, and result are stored in the stack memory for the duration of the method execution. ### Stack OverflowError in Java In cases where there's insufficient space to create new objects, the system may raise a java.lang.StackOverFlowError. Notably, the elements within the stack memory have a scope limited to their respective threads. Each thread in the Java Virtual Machine (JVM) has a dedicated stack. An example demonstrates how this error occurs. ```java // Java code snippet causing StackOverflowError public class StackOverflowExample { public static void main(String[] args) { try { recursiveMethod(1); } catch (StackOverflowError e) { System.out.println("StackOverflowError caught: " + e.getMessage()); } } // A recursive method that causes a StackOverflowError public static void recursiveMethod(int counter) { System.out.println("Counter: " + counter); recursiveMethod(counter + 1); } } ``` **Explanation:** The main method is called recursiveMethod with an initial counter value of 1. The recursiveMethod prints the current counter value and then calls itself with an incremented counter. This process continues indefinitely, leading to an infinite recursion. Eventually, the stack memory is exhausted, resulting in a StackOverflowError. ## Heap Allocation in Java Heap memory is established during the Java Virtual Machine (JVM) initiation and remains in use throughout the application's runtime. It is the storage ground for objects and Java Runtime Environment (JRE) classes. When objects are created, they claim space in the heap memory, with their references stored in the stack. Differing from the stack's orderly Last-In-First-Out (LIFO) approach, heap memory operates dynamically, handling memory blocks without adhering to a specific order. In Java, memory management is automated, thanks to the garbage collector, which is responsible for deallocating objects no longer in use. Heap memory persists until one of two events occurs: the program terminates, or a memory-freeing event occurs. The elements within heap memory are globally accessible throughout the application and are shared among all threads. The heap memory is further categorized into distinct memory areas: the Young generation, Survivor space, Old generation, Permanent generation, and Code Cache. ### Examples: An example illustrates the allocation of a variable in the stack and an object in the heap. ```java // Java code snippet public class HeapMemoryExample { public static void main(String[] args) { // Creating objects in heap memory Person person1 = new Person("Alice", 25); Person person2 = new Person("Bob", 30); person1.displayDetails(); person2.displayDetails(); } } class Person { private String name; private int age; // Constructor for initializing object properties public Person(String name, int age) { this.name = name; this.age = age; } // Displaying object details public void displayDetails() { System.out.println("Name: " + name + ", Age: " + age); } } ``` **Output:** ``` Name: Alice, Age: 25 Name: Bob, Age: 30 ``` **Explanation:** In the above program, Objects of the Person class are created using the new keyword and stored in the heap memory. ### Why is OutOfMemoryError thrown in Java? OutOfMemoryError occurs when there's insufficient space in the heap to create and store new objects, or if the heap space reaches total capacity, the system raises java.lang. OutOfMemoryError. An example showcases this error. ```java // Java code snippet causing OutOfMemoryError import java.util.ArrayList; import java.util.List; public class OutOfMemoryExample { public static void main(String[] args) { try { List<Object> objectList = new ArrayList<>(); while (true) { objectList.add(new Object()); } } catch (OutOfMemoryError e) { System.out.println("OutOfMemoryError caught: " + e.getMessage()); } } } ``` **Explanation:** A List of Objects is continuously populated in a while loop. The loop runs indefinitely, attempting to add new objects to the list. Eventually, the heap space is exhausted, leading to an OutOfMemoryError. ## Mixed Example of Both Memory Allocation An example demonstrates a Java program's simultaneous usage of stack and heap memory. ```java // Java code snippet combining stack and heap allocation public class MemoryAllocationExample { // Class-level variable stored in the heap memory private static int classVariable = 10; public static void main(String[] args) { // Local variables stored in the stack memory int stackVar1 = 5; int stackVar2 = 7; // Creating an object in the heap memory MyClass myObject = new MyClass("John", 25); // Accessing and modifying stack and heap variables System.out.println("Stack Variables: " + stackVar1 + ", " + stackVar2); System.out.println("Class Variable (Heap): " + classVariable); myObject.displayDetails(); } } class MyClass { // Instance variables stored in the heap memory private String name; private int age; // Constructor for initializing object properties public MyClass(String name, int age) { this.name = name; this.age = age; } // Displaying object details public void displayDetails() { System.out.println("Object Details (Heap): Name: " + name + ", Age: " + age); } } ``` Output: ``` Stack Variables: 5, 7 Class Variable (Heap): 10 Object Details (Heap): Name: John, Age: 25 ``` ## Key Difference Between Heap and Stack Memory in Java In the realm of memory management, distinctions arise between stack and heap allocation: 1. **Automatic Management:** * Stack: Compiler automates both allocation and de-allocation of memory. * Heap: Manual intervention by the programmer is required for memory management. 2. **Cost of Handling Frames:** * Stack: More efficient and less resource-intensive. * Heap: Handling heap frames incurs higher costs. 3. **Memory Shortage and Issues:** * Stack: Prone to memory shortage issues. * Heap: Faces challenges primarily related to fragmentation. 4. **Frame Access and Cache Considerations:** * Stack: Easier frame access is cache-friendly due to a compact memory region. * Heap: Frame access is more complex as frames are dispersed, increasing cache misses. 5. **Flexibility of Memory Size:** * Stack: Inflexible, memory size is fixed. * Heap: Flexible, allowing for dynamic adjustments to the allotted memory. 6. **Access Time:** * Stack: Faster access time. * Heap: Slower access time compared to the stack. ## Heap Vs Stack Memory Allocation in Java: Comparative Analysis A tabular overview comparing various aspects of Heap and Stack memory in Java is given below-. | Property | Stack Memory | Heap Memory | |-----------------|------------------------------|--------------------------------| | Size | Smaller, fixed size | Larger, dynamic size | | Order | LIFO | No specific order | | Speed | Faster access | Slower access | | Resizing | Not allowed | Allowed | | Allocation | Automatic for method scope | Manual for objects, GC reclaim | | Storage | Method-specific and references | Objects and JRE classes | | Exception | StackOverflowError | OutOfMemoryError | | Thread Safety | Thread-specific, thread-safe | Shared, not thread-safe | | Scope | Method-specific | Global | | Lifetime | Short-lived | From start to end of execution | ## Conclusion * The Stack Memory utilizes Static Memory Allocation, storing function calls, method-specific data, and object references. * Stack follows LIFO Order. * Heap is the storage ground for objects and Java Runtime Environment (JRE) classes. * Heap follow FIFO Order. ## Related Topics - [StackOverflowError in Java](https://www.scaler.com/topics/stackoverflowerror/) - [Garbage Collection in Java](https://www.scaler.com/topics/garbage-collection/) - [Java Memory Management](https://www.scaler.com/topics/java-memory-management/)