Java成员变量的引用在JVM内存中的存储位置咨询
Hey there! Let's break down where each variable in your code lives in the JVM, and specifically answer your question about member variable references.
First, let's recap your code for clarity:
class A { // Member variables int i = 2; Integer j = new Integer(3); public static void main(String[] args){ // Local variables int a = 2; Integer b = new Integer(3); } }
Key Memory Regions to Know
Before diving in, remember two core JVM memory areas relevant here:
- Heap: Stores all object instances and the member variables of class instances (whether they're primitive types or reference types).
- Java Virtual Machine (JVM) Stack: Stores local variables (for methods) — primitive type values directly, and references to objects (which live in the heap).
Breakdown of Each Variable
Member variable
int i = 2- Since
iis a primitive-type member variable, its value (2) is stored directly in the heap memory when an instance ofAis created. It's part of theAobject instance itself.
- Since
Member variable
Integer j = new Integer(3)- The
new Integer(3)creates an Integer object instance, which lives in the heap. - The reference
j(which points to that Integer object) is also stored in the heap — becausejis a member of theAinstance, and all parts of the instance live in the heap.
- The
Local variable
int a = 2- This is a primitive-type local variable in the
mainmethod. Its value (2) is stored directly in the local variable table of themainmethod's stack frame (part of the JVM Stack).
- This is a primitive-type local variable in the
Local variable
Integer b = new Integer(3)- The
new Integer(3)object instance lives in the heap. - The reference
b(pointing to that Integer object) is stored in the local variable table of themainmethod's stack frame (JVM Stack).
- The
Your Core Question: Where are member variable references stored?
As we saw with j above: member variable references are stored in the heap. Because member variables are part of a class instance, and all class instances reside in the heap — so every part of that instance (including references to other objects) lives right alongside it in the heap.
内容的提问来源于stack exchange,提问作者SnailMann

