Java Memory Model Explained with a Simple Example
Understanding where variables and objects are stored in Java is a common interview topic and an important foundation for writing efficient and safe code.
Java divides memory at runtime into several areas:
-
Method Area (Metaspace)
-
Heap
-
Stack
-
String Constant Pool
Let’s understand all of them using one simple class and object.
✅ Example Program with JVM Memory Comments
๐ง How the Memory Looks at Runtime (Conceptual View)
๐งช Variable Type vs Memory Location
| Variable Type | Example | Stored In |
|---|---|---|
| Local variable | int hours | Stack |
| Reference variable | Employee e | Stack |
| Instance variable | id, name | Heap |
| Static variable | company | Method Area |
| String literal | "Vinod" | String Pool |
๐ฏ Interview-Ready Explanation
Local variables and references are stored on the stack, objects and instance variables are stored in the heap, static variables are stored in the Method Area, and string literals are stored in the String Constant Pool.
๐ One-Line Takeaway
Stack stores method data, Heap stores objects, Method Area stores class data, and String Pool stores string literals.
No comments:
Post a Comment