Can I print the (decimal) memory address of a pointer in Java?


My Data Structure and Organization teacher insists that you can print the memory address of a pointer (when working with nodes) in decimal, and I've searched everywhere, to no avail.

It's possible?


Java does not have pointers in the strict sense of native programming languages ​​like co pascal. One of the central ideas of the JVM is to remove all memory management from the hands of the programmer. So you have objects or references , but no pointers.

Having said that, it is obvious that these objects are stored somewhere in memory and therefore have an address . You must take into account that the JVM is free to move an object from one place to another in memory, after it has been created (and in fact, it does), so it is also not safe to keep a reference to a memory address, for the object may no longer be there.

All that being said, the answer to your question is: yes it is possible , using sun.misc.Unsafe . To do this, I replicate the code for the printAddresses() function posted in this StackOverflow answer , which is in turn based on this other answer on the same site.

public static void printAddresses(String label, Object... objects) {
    System.out.print(label + ": 0x");
    long last = 0;
    int offset = unsafe.arrayBaseOffset(objects.getClass());
    int scale = unsafe.arrayIndexScale(objects.getClass());
    switch (scale) {
    case 4:
        long factor = is64bit ? 8 : 1;
        final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor;
        last = i1;
        for (int i = 1; i < objects.length; i++) {
            final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor;
            if (i2 > last)
                System.out.print(", +" + Long.toHexString(i2 - last));
                System.out.print(", -" + Long.toHexString( last - i2));
            last = i2;
    case 8:
        throw new AssertionError("Not supported");

You can do a test like this:

    System.out.println("Hashcode :       "+myObject.hashCode());
    System.out.println("Hashcode :       "+System.identityHashCode(myObject));
    System.out.println("Hashcode (HEX) : "+Integer.toHexString(myObject.hashCode()));

    System.out.println("toString :       "+String.valueOf(myObject));

    printAddresses("Address", myObject);

Which will produce output similar to this:

Hashcode :       125665513
Hashcode :       125665513
Hashcode (HEX) : 77d80e9
toString :       java.lang.Object@77d80e9
Address: 0x7aae62270

The address, as you can see, is printed in hexadecimal.

Scroll to Top