Library contents

Groovy String.valueOf

Convert a primitive, an object or character-array data into a String using the selected overload.

A simple example

String.valueOf

  1. Start with The integer 2
  2. Do this Convert to text
  3. Result "2"
The result is a character string that you can join to other text.

Syntax

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

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

ResultSeats 24
Lesson.groovy
println "Seats " + String.valueOf(24)
Output
Seats 24

An integer becomes its decimal representation.

Advertisements

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.

Result[null]
Lesson.groovy
Object note = null
println "[" + String.valueOf((Object) note) + "]"
Output
[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?

GivenPrefix “Ticket ” + 1
Worked resultTicket 1

What to watch for

Calling valueOf on a null Object returns the text null. A null char array selects a different overload and throws.

Documentation for String.valueOf