You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java成员变量的引用在JVM内存中的存储位置咨询

JVM Memory Storage Breakdown for Your Code

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

  1. Member variable int i = 2

    • Since i is a primitive-type member variable, its value (2) is stored directly in the heap memory when an instance of A is created. It's part of the A object instance itself.
  2. 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 — because j is a member of the A instance, and all parts of the instance live in the heap.
  3. Local variable int a = 2

    • This is a primitive-type local variable in the main method. Its value (2) is stored directly in the local variable table of the main method's stack frame (part of the JVM Stack).
  4. 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 the main method's stack frame (JVM Stack).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:45:51