Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java references values are addresses values?

When I do:

int x[] = new int[2];
System.out.println("...> " + x);

the output value is like this: [I@1b67f74

so that hex number is concerning to the memory address where the object has been allocated?

and [I what does it meaning?

like image 484
xdevel2000 Avatar asked May 24 '26 15:05

xdevel2000


1 Answers

No, that hex number should not be interpreted as the memory address where the object is located. In fact, it is the hash code of the object. The API documentation of Object.toString() says:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

 getClass().getName() + '@' + Integer.toHexString(hashCode())

The API documentation of java.lang.Object.hashCode() says:

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

So for Sun's JVM, if you don't override the hashCode() method, then it's indeed the memory address of the object, but there is no guarantee that this is so, so you shouldn't depend on it.

There is no (real, reliable) way (that works on any JVM) to get the memory address of an object in pure Java; Java does not have pointers, and references are not exactly the same as pointers.

Section 4.3.2 of the Java Virtual Machine Specification explains what the [I means; in this case it means your variable is an array of int.

like image 53
Jesper Avatar answered May 26 '26 03:05

Jesper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!