JVM Memory Basics: Heap, Stack, MetaSpace

𝙃𝙤𝙬 𝙅𝙑𝙈 𝙈𝙚𝙢𝙤𝙧𝙮 𝙒𝙤𝙧𝙠𝙨 (𝙃𝙚𝙖𝙥, 𝙎𝙩𝙖𝙘𝙠, 𝙈𝙚𝙩𝙖𝙎𝙥𝙖𝙘𝙚) — 𝙎𝙞𝙢𝙥𝙡𝙚 𝙀𝙭𝙥𝙡𝙖𝙣𝙖𝙩𝙞𝙤𝙣 Understanding JVM memory is a must for every Java backend developer. Almost every interviewer asks this in some form. Here’s the simplest explanation 👇 1️⃣ JVM divides memory into two main parts: Heap and Stack ✅ Stack Memory Used for: method calls local variables function arguments Fast and automatically cleaned up when a method finishes. Example: int x = 10; // stored in stack Each thread has its own stack. --- 2️⃣ Heap Memory (big area) Used for storing objects: User u = new User(); // stored in heap Heap is shared by all threads. Garbage Collector cleans the heap. Heap is divided into: --- 2.1 Young Generation (new objects) Eden → new objects created here Survivor S0/S1 → objects that survive a few GC cycles Frequent “minor GC” happens here. --- 2.2 Old Generation (long-lived objects) If an object stays alive long enough, it moves here. GC here is called “major GC”. --- 3️⃣ MetaSpace (stores class information) This is where JVM stores: class definitions methods metadata Replaced “PermGen” after Java 8. It grows automatically based on need. --- 4️⃣ Simple Flow 1. Program starts 2. Methods → stack 3. Objects → heap 4. Class info → metaspace 5. Garbage Collector removes unused heap objects 💡 In short Stack → method-level data, very fast Heap → objects, cleaned by GC Young Gen → new objects Old Gen → long-living objects MetaSpace → class and metadata Once you understand this, debugging memory leaks, GC issues, and OutOfMemory errors becomes much easier. #Java #JVM #BackendDevelopment #InterviewPrep #JavaInternals #CleanCode #CodingConcepts #techieanky #javainterview #prepration #concept

To view or add a comment, sign in

Explore content categories