Java String.format
Build formatted text from a format string and a sequence of arguments.
A simple example
String.format
- 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(String.format("[%s]", "A"));
}
}
[A]
Syntax
public static String format(String format, Object... args)
JDK 21 method signatures (2)
public static String format(String format, Object... args)
public static String format(Locale l, String format, Object... args)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaPrint a zero-padded queue ticket
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(String.format(java.util.Locale.ROOT, "Q-%03d", 7));
}
}
Q-007
A minimum width of three pads the number with zeros.
Show a measured weight to one decimal place
A parcel scale records more precision than the printed label can show. Format the measured weight to the specified number of decimal places without altering the underlying reading.
class Main {
public static void main(String[] args) throws Exception {
System.out.println(String.format(java.util.Locale.ROOT, "%.1f kg", 2.75));
}
}
2.8 kg
The display rounds to one decimal place while the stored numeric value is unchanged.
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
Choose a locale for machine-readable output. A conversion that is incompatible with its argument type throws an exception.