Java 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]"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("[%s]".formatted("A"));
}
}
[A]
Syntax
public String formatted(Object... args)
JDK 21 method signatures (1)
public String formatted(Object... args)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint a student and course on one label
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.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("%s — %s".formatted("Ada", "Biology"));
}
}
Ada — Biology
Each string fills the next placeholder in the template.
Show a literal percent sign in a notice
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.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("Attendance target: %s%%".formatted("90"));
}
}
Attendance target: 90%
The doubled percent sign prints one literal 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.