I was reading the docs and noticed it. Never imaginated it. The description:
This object (which is already a string!) is itself returned.
Besides filling conventions or using computing resources, what does a .toString() in Java do on a String that using the String itself wouldn’t? Why doesn’t it simply inherit the .toString() from class java.lang.Object?
EDIT:
I understand that in situations of polymorphism an own toString() method has to exist since it overrode its parent’s toString(). What I want to know in the first question is if there is any situation where you’ll get something different between using stringVariable/"String value" and using stringVariable.toString()/"String value".toString().
Ex. gr.: An output operation like System.out.println(stringVariable.toString()); or a value assignment like stringVariable = "String value".toString();.
It means it gives an appropriate result when called polymorphically.
Because that wouldn’t give the same result, and almost certainly not the desired result.
Object.toString()is meant to give a reasonably useful string representation of the object. TheObjectimplementation gives information about the type and a value which can be used for crude identity hints (diagnostically useful, but that’s all). That’s clearly not the most useful string representation for a string – the string itself is.While I would say that it’s a pity that
toStringis defined in quite a woolly way (it’s not clear whether the result is meant for machine, developer or user consumption), it feels obvious to me that aStringwould return itself in the implementation.