Difference between Stack and Heap in Java
In Java, both the stack and the heap are areas of memory that serve different purposes during program execution.
Table of Contents
1. Stack
- The stack is a region of memory that stores method invocations and local variables for each thread in a Java application.
- Each thread in Java has its own stack, which is used for method calls and local variable storage.
- The stack follows a Last-In, First-Out (LIFO) structure, meaning that the most recently called method is at the top of the stack, and when a method completes execution, it is removed from the stack.
- The stack is relatively small in size and has a fixed memory allocation Difference between Stack and Heap in Java determined by the JVM.
- The stack is used for storing primitive data types, references to objects, and method call information.
2. Heap
- The heap is a region of memory that stores objects and arrays created during the execution of a Java application.
- All objects in Java are allocated memory on the heap, regardless of whether they are created as local variables within a method or as instance variables of an object.
- The heap is dynamic in size and grows and shrinks as needed during the execution of the program.
- Objects on the heap can be accessed from anywhere in the program, and their lifetime is not tied to any specific method or thread.
- Java’s garbage collector manages memory allocation and deallocation on the heap, reclaiming memory from objects that are no longer reachable by the program.
Here’s a Java example to illustrate the difference between the stack and heap:
Example
java
public class StackVsHeapExample {
public static void main(String[] args) {
// Stack variables
int a = 5;
String b = "Hello";
// Heap objects
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
}
}
class MyClass {
// Instance variables
private int x;
private String y;
// Constructor
public MyClass() {
x = 10;
y = "World";
}
}
Stack and Heap Example
The variables a and b are stored on the stack, as they are primitive types and local variables within the main() method. On the other hand, the objects obj1 and obj2 of type MyClass are created on the heap using the new keyword. The MyClass objects have instance variables x and y, which are also stored on the heap. The stack maintains the method call stack and local variables, while the heap stores dynamically allocated objects and their data.