Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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?

like image 975
Madhu Avatar asked Jan 17 '11 10:01

Madhu


People also ask

What does the object toString () method do by default?

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.

What is the purpose of the hashCode () method?

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.

How does the default hashCode () work?

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.

What is the default toString method in Java?

By default, the toString() method is called by println, but the method can also be called explicitly on any object.


2 Answers

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.

like image 93
thkala Avatar answered Sep 22 '22 04:09

thkala


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

like image 41
Sainath S.R Avatar answered Sep 23 '22 04:09

Sainath S.R