Groovy String.valueOf
Convert a primitive, an object or character-array data into a String using the selected overload.
A simple example
String.valueOf
- Start with The integer 2
- Do this Convert to text
- Result "2"
Syntax
public static String valueOf(Object obj)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyTurn a numeric count into a label
The booking screen keeps a numeric count internally and prints it beside a text label. Convert at display time so the same count remains available for arithmetic when another booking is made.
println "Seats " + String.valueOf(24)
Seats 24
An integer becomes its decimal representation.
Display a missing optional object
An optional field may be absent when a receipt or notice is displayed. Decide what that missing value should look like on the screen before treating the converted text as a user-supplied note.
Object note = null
println "[" + String.valueOf((Object) note) + "]"
[null]
The Object overload produces a printable missing-value marker.
Print the first entry tag
A coat-check desk numbers the first ticket one. The ticket printer includes the number as ordinary decimal text after a prefix. What does the completed label say?
What to watch for
Calling valueOf on a null Object returns the text null. A null char array selects a different overload and throws.