0
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?

DCR
  • 14,737
  • 12
  • 52
  • 115
  • 1
    How do you know the addresses of `x`, `luna` and the `Cat` object (those numbers doesn't look quite right to me)? The actual memory addresses in Java [aren't really useful](https://stackoverflow.com/a/1961150/5133585) anyway. Or are you asking a theoretical question with those assumptions? – Sweeper Oct 16 '21 at 19:11
  • @Sweeper they are, if you use Unsafe and need to access an Object by the offset; but I agree, this sounds purely theoretical. And for that purpose there is `jol` – Eugene Oct 16 '21 at 19:29
  • @Eugene Whats jol? And yes this is theoretical for classroom discussion – DCR Oct 16 '21 at 19:35
  • [Java Object Layout.](https://github.com/openjdk/jol) – Sweeper Oct 16 '21 at 19:36
  • Name is a String – DCR Oct 16 '21 at 19:43
  • As those numbers are odd, they definitely aren't real memory addresses. – Boann Oct 16 '21 at 23:42

1 Answers1

1

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306