You’ve written Java code. But do you know how it actually runs in memory?
Java has two main memory areas: Stack and Heap. Understanding them helps you write faster, safer, and more efficient code.
Let’s break it down simply 👇
Stack Memory
-
Stores method calls and local variables
-
Works like a stack of plates — last in, first out (LIFO)
-
Fast, but small in size
-
Each thread has its own stack
public void greet() {
String name = "Aarav"; // stored in stack
}
✅ Automatically cleaned up when the method ends
❌ Only holds simple, short-lived data
❌ Only holds simple, short-lived data
Heap Memory
-
Stores objects created with
new
-
Shared by all parts of the program
-
Bigger and slower than stack
-
Needs garbage collection
Student s = new Student(); // s is in stack, object is in heap
Student s = new Student(); // s is in stack, object is in heap
No comments:
Post a Comment