Library contents

Groovy String.formatted

Use a string itself as the format template and supply values for its placeholders.

A simple example

String.formatted

  1. Start with Text A, template [value]
  2. Do this Insert text between brackets
  3. Result "[A]"
Formatting keeps the brackets and fills the single space reserved for a value.

Syntax

Groovy syntax
public String formatted(Object... args)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

Print a roster entry

A printer receives badge or ticket data in separate fields. Use the display format required by the desk so names, numbers and separators occupy their intended places on the finished label.

ResultAda / Lab
Lesson.groovy
println "%s / %s".formatted("Ada", "Lab")
Output
Ada / Lab

Each placeholder consumes the next argument.

Advertisements

Show a literal percent sign

A printed notice must display a percentage and uses a formatter that treats the percent sign specially. Escape the literal mark in the format string so it survives the formatting step.

Result85%
Lesson.groovy
println "%s%%".formatted("85")
Output
85%

A double percent sign renders as one percent sign.

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

formatted uses the default formatting locale. Use String.format with an explicit locale when locale-sensitive output must be reproducible.

Documentation for String.formatted