Java explain how objects are stored in memory [closed]

int x = 5                               Cat luna = new Cat()
Address           Value                 address       reference
669cf9            5                     723ecf        683ec5

If Cat:

public class Cat{
  private String name;

  public void talk(){
      System.out.println("meow");
  }
}

How can I show what’s at memory address 683ec5?

Answer

Objects are stored in memory as a block of fields with Object headers. You can take a look at jol to see how Objects are actually laid out in memory. Each object has header, fields might have padding, fields might take more space than you think (boolean), etc.

You can take a look at this example where I tried to explain things a little more, but the github page about jol is extensive in its examples.

At the bytecode level accessing an Object field is boring, to be honest, but you can take a look for sure at what javac produces (with javap). When code is executed on the CPU, you will see different offsets when trying to get a certain field, like:

mov    0x10(%rsi),%r10

this is accessing “something” at a certain 16 offset (0x10 is an offset here). Think about an Object like a stack, accessing fields – you need to know how big each one is (VM tracks that) and the beginning address of the stack, the rest is easy.

The MUST read here if you really want to know things starts from this page.