36

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?

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Madhu
  • 5,686
  • 9
  • 37
  • 53

3 Answers3

36

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.

thkala
  • 84,049
  • 23
  • 157
  • 201
  • Thanks for your response. Sorry for asking you this, IS there any spec explaining about this? – Madhu Jan 17 '11 at 10:37
  • Reading the javadoc comments on java.lang.Object explains at least parts of it. – Erik Jan 17 '11 at 10:46
  • Well, Its like we got to assume the reason why so. But there is no exact explanation isn't? – Madhu Jan 17 '11 at 10:51
  • I believe the contract is that objects for which equal returns true MUST return the same hashcodes. – Dunes Jan 17 '11 at 10:51
18

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().

JeremyDouglass
  • 1,361
  • 2
  • 18
  • 31
Sainath S.R
  • 3,074
  • 9
  • 41
  • 72
5

From the javadocs:

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.)

The hashCode appears in the string representation of the object so that you can distinguish this object from other objects of the same class. This can be useful for debugging.

dogbane
  • 266,786
  • 75
  • 396
  • 414
  • actually System.identityHashCode nowadays is using an assigned random number (since the address is far from 'stable') – bestsss Jan 17 '11 at 12:11