Where are the member variables of the Java object stored

public class A{
    public static void main(String[] args){
        B b = new B();
    }
}

public class B{
    int i;
    C c;
    B(){
        i = 1;
        c = new C();
    }
}

public class C{

}

it is generally said that the reference is on the stack and the object instance is on the heap. For this piece of code, b is on the stack and the B instance that b points to is on the heap.
excuse me, where can I be stored?
2.When the C instance is on the heap, where is the reference c of the C instance stored?
3. What is stored in the space where instance B is located (is it a reference or an instance)?

Jul.20,2021

just remember one principle: the reference variables and basic types of variables in the method body are on the stack, and the rest are on the heap.

so everything in the B object is on the heap, and the b variable in the main method is on the stack.


take 32-bit as an example, instance B of the program stores object header (8 bytes) + instance data I (4 bytes) + C object reference c (4 bytes) = 16 bytes
so I is stored in B instance, and C object reference c is also placed in B object.


each class of java has its own stack. The member variable pointer is on the stack. If the member variable is a class, it is in the heap.

Menu