Groovy 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"
Syntax
public String toString()
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyDisplay 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.
CharSequence label = "paid"
println label.toString()
paid
The underlying object already contains the final text.
Check String conversion identity
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.
String label = new String("room")
println label.is(label.toString())
true
Groovy is tests object identity.
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.