Questions

Forum Navigation
Please to create posts and topics.

Why does the default Object.toString() include the hashcode? (Java)

If you execute:

System.out.println(someObj.toString());

You probably see the output like:

someObjectClassname@hashcodenumber

Why?

The object hashcode 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 hashcode.

The default toString() method shows the object class and its hashcode 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.

Someone 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 representation of the same hashcode .

Integer.toHexString(object.getHashcode);

It will return the same value returned by object.toString().