How to print address of a variable in Java

There is no way to get the memory address of anything in Java. All that is hidden by the JVM, you never have to worry about it.
Even if you could get it, you couldn't do anything with it...

Instead, you identify objects by other means, typically by implementing their equals() and hashCode() methods.


It is impossible to get an address of any primitive variable or object in Java. All that you can do is get default object hash code (which usually related to its address, but it is not guaranteed) with System.identityHashCode(a).


There is no element in the java language that allows you the get the address of anything and more importantly there is no language element ever requiring an address for anything. Thats why there is no address-of operator in java. The whole language is designed to work without.

The whole concept of memory address is abstracted in java; the closest you can get is a reference, but that is limited to actual objects. While the reference's value is actually a memory address (or at least something easily convertible into a memory address, see compressed OOPS), there is no way of converting that value to anything else. And again there is no need to ever do this, except maybe for satisfying your curiosity.

It is however possible, by using the (attention: not portable, not meant for actual public use!) java.sun.misc.Unsafe, this class allows converting the value of a reference to a long (representing a memory address). Example for using it can be found here: https://dzone.com/articles/understanding-sunmiscunsafe.