In Java, String.toString() simply returns this: the very same string object, not a copy. A string is already a string, so there is nothing to convert.
The method exists because every class inherits toString() from Object, and code that works with Object or CharSequence variables calls it to get text. String overrides it so that such code receives the characters instead of a class name and hash.
toString() is an instance method of java.lang.String, available since JDK 1.0. Call it on a string, as in text.toString(); calling it on a null reference throws NullPointerException.
Syntax
Call it with no arguments. You rarely need it on a variable whose type is already String.
println and string concatenation call toString() for you on objects, which is why "value: " + obj works. For a null reference they print null instead of calling the method.
Library declarations
java
public String toString();
Parameters
Parameter
Description
None
toString() takes no parameters.
Return Value
Return Value
Description
String
This string object itself.
Java Examples
Example 1 — toString() Returns the Same Object
Compare references to see that no copy is made.
java
public class ToStringSameObject {
public static void main(String[] args) {
String s = "hello";
String t = s.toString();
System.out.println(t);
System.out.println("same object? " + (s == t));
String copy = new String("hello");
System.out.println("copy == original? " + (copy.toString() == s));
}
}
Output
hello
same object? true
copy == original? false
How It Works
No conversion needed.s.toString() returns the reference it was called on, so t prints "hello".
Identity check.s == t is true: both variables point at one object.
Each object returns itself.copy.toString() returns copy, a different object from the literal, so the last comparison is false.
Example 2 — Calling toString() Through Object and CharSequence
The same call works for many types; each class supplies its own text.