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

🚀 Top 3 Java Projects Every Beginner Should Build (With Code Ideas)

 Tired of just printing "Hello World"? It’s time to build something real. 💻 If you're learning Java and want to stand out, ...