Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 402
Vishal Sharma Avatar asked Nov 30 '22 21:11

Vishal Sharma


1 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?

like image 163
Sweeper Avatar answered Dec 05 '22 04:12

Sweeper