Java String.toString
Return the same String instance when a text-oriented API requests its string representation.
A simple example
String.toString
- Start with "AB" as a String
- Do this Ask for its string form
- Result "AB"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("AB".toString());
}
}
AB
Syntax
public String toString()
JDK 21 method signatures (1)
public String toString()Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDisplay a course code from a generic text field
A display component receives text through a general-purpose interface. Convert or transform the supplied value at the boundary where the component needs the final printable label.
class Main {
public static void main(String[] args) throws Exception {
CharSequence field = "CS101";
System.out.println(field.toString());
}
}
CS101
The runtime object is already a String, so its content is already in the required form.
Check whether conversion copies a receipt label
A display helper already holds an ordinary string and is asked to convert it to text. Check what it returns so the caller understands the difference between displaying a value and making an independent copy.
class Main {
public static void main(String[] args) throws Exception {
String label = new String("paid");
System.out.println(label.toString() == label);
}
}
true
The identity check illustrates the String contract. Use equals for ordinary text comparison.
Read a parcel sorting code
The depot scans a parcel marked NC-17. The program recovers the text of this existing string for a scanner log. What exact sequence of characters should survive?
What to watch for
Other CharSequence implementations have different toString behaviour. Converting a String does not copy or normalize it.