本文由 AI 分析生成
建立時間: 2026-03-28 來源: https://blog.marklee.tw/java-interview-jvm-stack-heap/
Summary
Chinese-language reference article on JVM memory model, specifically the Stack vs. Heap distinction for Java interviews. Covers Java data types (Primitive vs. Reference), how each is stored in Stack/Heap, and the role of Garbage Collection.
中文 JVM 記憶體模型參考文章,專注於 Java 面試中的 Stack 與 Heap 的區別。涵蓋 Java 數據類型(基本類型與參考類型)、每種類型在 Stack/Heap 中的存儲方式,以及垃圾回收的角色。
Key Points
- Stack: per-thread, FILO structure; stores local variables, function parameters, return addresses; predictable lifecycle managed by JVM automatically
- Heap: shared across threads; stores object instances (Reference/Class Types); lifecycle unpredictable → managed by Garbage Collection
- Java data types: (1) Primitive (int, long, boolean, etc.) — stored as actual values in Stack; (2) Reference/Class types (Integer, String, user-defined) — instance stored in Heap, reference (memory address) stored in Stack
User user = new User("Mark")→ instance stored at Heap address (e.g., 0x1234) → address stored in Stack variableuser- GC handles Heap cleanup; collects objects with no reachable references from GC Roots (reachability analysis)
- Naming confusion: Stack ≠ stack data structure; Heap ≠ heap data structure — these are JVM memory regions
Insights
The key interview point is the Reference Type pattern: a Stack variable for a Reference Type holds a memory address (pointer), not the object itself. Understanding this explains why == compares references (not values) for objects, why passing objects to methods can mutate them, and why null pointer exceptions occur. The GC Roots reachability analysis explanation is the essential mental model for understanding when objects are eligible for garbage collection in Java.
Connections
Raw Excerpt
Stack 存取速度快,但資料長度及生命週期必須是預知的。Heap 是 Class Type 創建實例時存放資料的地方。若是 Class / Reference Type,實例資料會儲存在 Heap 中,Stack 內的變數值為實例在 Heap 中的記憶體位址。