Where are instance variables of an Object stored in the JVM?

后端 未结 3 1412
礼貌的吻别
礼貌的吻别 2020-12-13 15:53

Is an instance variable of an object in Java stored on the stack or method area of the JVM?

Also, do we have different instance variable for multiple threads?

3条回答
  •  时光说笑
    2020-12-13 16:23

    Most of the JVM implementation divides memory into following parts:

    1. Method Area
    2. Stack
    3. Heap
    4. pc registers
    5. Native method stacks.

    Lets talk about Method Area, Stack and Heap only.

    For e.g Take a class

    class Lava {
      int i = 5;
      static int j = 10;
      void flow() { //some implementation}
     }
    

    When an instance of this object is created from a class X

    Lava l = new Lava();
    

    First, Class type of Lava, i.e. Lava.class is stored in your Method area, with details like methods, fields and other referencing type. Also static variables like j in our example is stored in Method area itself.

    Second the instance of Object Lava is stored in Heap Area as well as its instance variable i.e i.

    Third, Its reference, i.e l in our example is stored in Stack area, which point to instance that is created in Heap.

提交回复
热议问题