Groovy String.formatted
Use a string itself as the format template and supply values for its placeholders.
A simple example
String.formatted
- Start with Text A, template [value]
- Do this Insert text between brackets
- Result "[A]"
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.groovyPrint 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.
println "%s / %s".formatted("Ada", "Lab")
Ada / Lab
Each placeholder consumes the next argument.
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.
println "%s%%".formatted("85")
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?
What to watch for
formatted uses the default formatting locale. Use String.format with an explicit locale when locale-sensitive output must be reproducible.