toString() method of Object class

In the lecture Generic Bubble Sort, while displaying display(cars), it called the toString() function of Object class but how?

@d1sha_singh,
It happens in the print function of syso. The valueOf function call in syso is dependent on toString. Hence, that call happens internally.

valueOf function call in syso?

@d1sha_singh,

System.out.println(someObject) calls that object’s toString() function to convert the object to a string representation.

1 Like

May I get some detailed information regarding this concept, please? I’m still confused. Thanks for your support sir.

@d1sha_singh,

When you call System.out.println() with an arbitrary object as a parameter, you get the version of the function that acts on an Object

This version of the function

…calls at first String.valueOf(x) to get the printed object’s string value…

Looking at String.valueOf(Object), we see that it returns

if the argument is null, then a string equal to “null”; otherwise, the value of obj.toString() is returned.

So, System.out.println(someObject) calls that object’s toString() function to convert the object to a string representation.

If your object defines its own toString() function, then that is what will be called. If you don’t provide such a function, then your object will inherit toString() from one of its parent classes. In the worst case, it will inherit Object.toString()

That version of toString() is defined to return

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.

Or, in other words:

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

So, when you call System.out.println() on an object that doesn’t define its own version of toString(), you might get the Object version which looks like “classname@someHexNumber”.

1 Like

Thanks a lot sir. I may get back to you in case of further doubts.

1 Like

@d1sha_singh,
Sure. No problem :smile:

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.