Object.toString() does not return the hashcode value of the object in java but instead give some string

Viewed 939

I have written the following code:-

Test ob = new Test();
System.out.println(ob.toString());
System.out.println(ob.hashCode());

and the output is

Test@15db9742
366712642

i understand that the second value is the hashcode of the object and it is an integer value but i am not able to understand what is the first value. If it is the hashcode of the object then how can it be string and not integer

3 Answers

If you read the docs for toString very carefully:

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

366712642 in hex is exactly 15DB9742!

If it is the hashcode of the object then how can it be string and not integer?

As you can see from the docs, it is the class name, plus @, plus the dashcode, not just the hash code. Also, the method's name is toString. It would be weird if it returned an int, wouldn't it?

It represents classname@HashCode_in_Hexadeciaml_form. So, the string which you are seeing is actually the hexadecimal form of the integer hashcode

You can look the source code of Object.java. toString method is meant to provide information about class at runtime, so can be overriden. What you're doing is calling the default toString method from Object.java. It simply returns following:

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

Hence the output.

See code here

Related