Understanding Heap and Stack Memory in Java

💾 Heap vs Stack Memory in Java — Simplified! 🚀 In Java, memory is divided into two key areas — Heap and Stack. Understanding their roles helps you write efficient and bug-free code. 💡 🧠 Stack Memory: ➡️ Used for storing method calls and local variables. ➡️ Memory is automatically managed — created when a method starts, destroyed when it ends. ➡️ Fast and follows LIFO (Last In, First Out). ➡️ Example: int x = 10; 🔥 Heap Memory: ➡️ Used for storing objects and instance variables. ➡️ Managed by Garbage Collector (GC). ➡️ Slower but more flexible — data persists beyond method calls. ➡️ Example: Student s = new Student(); 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. Example Program: class Student {   String name; // stored in Heap   int age;   // stored in Heap   Student(String name, int age) {     this.name = name;     this.age = age;   } } public class MemoryExample {   public static void main(String[] args) {     int marks = 95; // Stored in Stack (local variable)     // Object stored in Heap, reference 's1' stored in Stack     Student s1 = new Student("Akash", 22);     System.out.println("Name: " + s1.name);     System.out.println("Age: " + s1.age);     System.out.println("Marks: " + marks);   } } ✅ Program Output: Name: Akash Age: 22 Marks: 95 💡 Explanation: The Student object is created in Heap memory with values "Akash" and 22. The reference variable s1 (which points to that object) is stored in Stack memory. The local variable marks is also in the Stack. When main() finishes execution: The Stack frame is cleared automatically. The Student object in the Heap remains until the Garbage Collector removes it. 📘 In short: ➡️ Stack = fast, temporary, method-specific. ➡️ Heap = shared, long-lived, object-specific. #Java #Programming #MemoryManagement #JavaDeveloper #CodingTips

To view or add a comment, sign in

Explore content categories