Library contents

Groovy String.toString

Return the same String instance when a text-oriented API requests its string representation.

A simple example

String.toString

  1. Start with "AB" as a String
  2. Do this Ask for its string form
  3. Result "AB"
A string already represents its own text. Calling toString preserves it.

Syntax

Groovy 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.groovy

Display 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.

From the programCharSequence label = "paid"
Resultpaid
Lesson.groovy
CharSequence label = "paid"
println label.toString()
Output
paid

The underlying object already contains the final text.

Advertisements

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.

Resulttrue
Lesson.groovy
String label = new String("room")
println label.is(label.toString())
Output
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?

GivenNC-17
Worked resultNC-17

What to watch for

Other CharSequence implementations have different toString behaviour. Converting a String does not copy or normalize it.

Documentation for String.toString