Thursday, 19 June 2025

Stack vs Heap in JAVA

 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

example - 
public void greet() {
    String name = "Aarav";  // stored in stack
}

✅ Automatically cleaned up when the method ends
❌ 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

👨‍💻 How I Started Learning Java at 15 (and You Can Too)

  When I first heard of Java, I thought it was just something to do with Minecraft mods or Android apps. I didn’t realize it would become my...