If you execute:
System.out.println(someObj.toString());
you probably see the output like
someObjectClassname@hashcodenumber
My question : Is there any specific reason why hashCode number is displayed there?
By default the toString() method will return a string that lists the name of the class followed by an @ sign and then a hexadecimal representation of the memory location the instantiated object has been assigned to.
The purpose of the hashCode() method is to provide a numeric representation of an object's contents so as to provide an alternate mechanism to loosely identify it. By default the hashCode() returns an integer that represents the internal memory address of the object.
In Java, hashCode() by default is a native method, which means that the method has a modifier 'native', when it is implemented directly in the native code in the JVM. Used to digest all the data stored in an instance of the class into a single hash value i.e., a 32-bit signed integer.
By default, the toString() method is called by println, but the method can also be called explicitly on any object.
The object hash code is the only standard identifier that might allow you to tell different arbitrary objects apart in Java. It's not necessarily unique, but equal objects normally have the same hash code.
The default toString()
method shows the object class and its hash code so that you can hopefully tell different object instances apart. Since it is also used by default in error messages, this makes quite a bit of sense.
See the description of the hashCode()
method for more information.
Adding something useful.
Some newbies may be confused as to why the hascode value returned via toString()
is different than what is returned via hashCode()
. This is because the toString()
method returns a hex representaion of the same hashcode .
Integer.toHexString(object.hashCode());
will return the same value returned by object.toString()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With