Does String's toString() method have any practical purpose?

user985358 picture user985358 · Jul 8, 2012 · Viewed 26.9k times · Source

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

Answer

Jon Skeet picture Jon Skeet · Jul 8, 2012

Besides filling conventions or using computing resources, what does a .toString() in Java do on a String that using the String itself wouldn't?

It means it gives an appropriate result when called polymorphically.

Why doesn't it simply inherit the .toString() from class java.lang.Object?

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. The Object implementation 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 toString is 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 a String would return itself in the implementation.