String formatting
suggest changeJava has printf-style formatting, modeled on C's printf. You write a format string with placeholders called format specifiers, and Java replaces each one with a formatted argument.
There are three common entry points, and they all accept the same format syntax:
String name = "Alice";
int age = 30;
// static method, returns a String
String s1 = String.format("%s is %d years old", name, age);
// instance method on the format string (Java 15+), returns a String
String s2 = "%s is %d years old".formatted(name, age);
// prints directly; %n is a platform-specific line separator
System.out.printf("%s is %d years old%n", name, age);
Alice is 30 years old
System.out.format(...) is the same as System.out.printf(...). PrintWriter, PrintStream and java.util.Formatter also have format methods that take this syntax.
Format specifier syntax
The general form of a specifier is:
%[argument_index$][flags][width][.precision]conversion
- conversion (required) says how to format the argument:
sfor a string,dfor an integer,ffor a decimal number, and so on - width: the minimum number of characters to output. Shorter output is padded with spaces
- precision: digits after the decimal point for
f/e, or the maximum number of characters fors - flags: change things like alignment, padding and signs
- argument_index: chooses an argument explicitly, e.g.
2$for the second argument
Common conversions
| Conversion | Argument type | Example | Result |
|---|---|---|---|
%s / %S |
any (uses toString()) |
"%S", "hi" |
HI |
%d |
int, long, BigInteger, ... |
"%d", 42 |
42 |
%x / %X |
integer, hexadecimal | "%X", 255 |
FF |
%o |
integer, octal | "%o", 8 |
10 |
%f |
float, double, BigDecimal |
"%.2f", 3.14159 |
3.14 |
%e / %E |
floating point, scientific | "%e", 12345.678 |
1.234568e+04 |
%g |
floating point, general | "%g", 0.00012345 |
0.000123450 |
%c |
char |
"%c", 'x' |
x |
%b |
any (null is false) |
"%b", null |
false |
%% |
none | "100%%" |
100% |
%n |
none | "a%nb" |
line separator |
An upper-case conversion (%S, %X, %E) upper-cases the result.
%s works with any object, including null (which prints null), collections ([1, 2, 3]) and your own classes, because it calls toString().
Width, alignment and padding
System.out.println(String.format("[%5d]", 42)); // [ 42] right-aligned in 5 chars
System.out.println(String.format("[%-5d]", 42)); // [42 ] left-aligned with '-'
System.out.println(String.format("[%05d]", 42)); // [00042] zero padded with '0'
System.out.println(String.format("[%.3s]", "hello")); // [hel] precision truncates strings
System.out.println(String.format("[%10.4s]", "abcdefgh")); // [ abcd]
Width and alignment are the basis of simple text tables:
System.out.println(String.format("%-10s|%8s", "Item", "Price"));
System.out.println(String.format("%-10s|%8.2f", "Coffee", 3.5));
System.out.println(String.format("%-10s|%8.2f", "Sandwich", 12.25));
Item | Price
Coffee | 3.50
Sandwich | 12.25
The article Aligning strings in console has more examples of column layouts.
Formatting numbers
Flags control signs, grouping separators and prefixes:
System.out.println(String.format("%+d", 42)); // +42 always show sign
System.out.println(String.format("% d", 42)); // " 42" space in place of a plus sign
System.out.println(String.format("%,d", 1234567)); // 1,234,567
System.out.println(String.format("%(d", -42)); // (42) negative in parentheses
System.out.println(String.format("%#x", 255)); // 0xff '#' adds the 0x prefix
System.out.println(String.format("%08X", 0xCAFE)); // 0000CAFE
System.out.println(String.format("%,.2f", 1234567.891)); // 1,234,567.89
System.out.println(String.format("%08.2f", -3.14159)); // -0003.14
For floating-point values, the precision sets the number of digits after the decimal point, and the value is rounded using RoundingMode.HALF_UP. The default precision for %f is 6:
System.out.println(String.format("%f", Math.PI)); // 3.141593
System.out.println(String.format("%.2f", Math.PI)); // 3.14
System.out.println(String.format("%10.3f", Math.PI)); // " 3.142"
System.out.println(String.format("%.3E", 12345.678)); // 1.235E+04
%d and %f also work with BigInteger and BigDecimal, with no loss of precision:
import java.math.BigDecimal;
import java.math.BigInteger;
System.out.println(String.format("%,d", new BigInteger("123456789012345678901234567890")));
// 123,456,789,012,345,678,901,234,567,890
System.out.println(String.format("%.2f", new BigDecimal("2.675"))); // 2.68
Negative integers in hexadecimal are shown in two's complement: String.format("%x", -1) gives ffffffff.
Argument indices
By default, each specifier uses the next argument. You can choose an argument with n$, or reuse the previous argument with <:
System.out.println(String.format("%2$s %1$s %2$s", "world", "hello"));
// hello world hello
System.out.println(String.format("%d in hex is %<x, in octal is %<o", 255));
// 255 in hex is ff, in octal is 377
Argument indices are useful in translated messages where word order differs between languages, and for date/time formatting, where you often format several fields of the same value:
import java.time.LocalDate;
LocalDate date = LocalDate.of(2024, 3, 9);
System.out.println(String.format("%tY-%<tm-%<td", date)); // 2024-03-09
For dates and times, prefer java.time.format.DateTimeFormatter. See Date Time Formatting.
Locale
Number formatting depends on the locale: the decimal separator, the grouping separator and the digits themselves. String.format(String, ...) uses the default locale, so the same code can give different output on different machines:
import java.util.Locale;
double d = 1234567.891;
System.out.println(String.format(Locale.US, "%,.2f", d)); // 1,234,567.89
System.out.println(String.format(Locale.GERMANY, "%,.2f", d)); // 1.234.567,89
For machine-readable output (CSV, JSON, logs, protocols) always pass a fixed locale such as Locale.ROOT or Locale.US. Otherwise a program running on a German system writes 3,14 where a parser expects 3.14.
"...".formatted(...) has no Locale overload. When the locale matters, use String.format(Locale, ...).
Formatting multi-line text
formatted works well with text blocks (Java 15+):
String report = """
Name: %s
Age: %d
""".formatted("Alice", 30);
System.out.print(report);
Name: Alice
Age: 30
Building output with Formatter
String.format creates a new Formatter on every call. To add many formatted pieces to one buffer, use a java.util.Formatter that writes to a StringBuilder (or to a file or stream):
import java.util.Formatter;
StringBuilder sb = new StringBuilder();
try (Formatter f = new Formatter(sb)) {
f.format("%-6s%5d%n", "apples", 3);
f.format("%-6s%5d%n", "pears", 12);
}
System.out.print(sb);
apples 3
pears 12
Errors
A format string is only checked at runtime. Mistakes throw a subclass of IllegalFormatException:
String.format("%d", "abc"); // IllegalFormatConversionException: d != java.lang.String
String.format("%d", 3.0); // IllegalFormatConversionException: d != java.lang.Double
String.format("%s %s", "x"); // MissingFormatArgumentException: Format specifier '%s'
String.format("%.2d", 3); // IllegalFormatPrecisionException: 2
Some things to watch for:
%ddoes not acceptdoubleand%fdoes not acceptint. Convert the value first or use the matching conversion- extra arguments are silently ignored:
String.format("%s", "a", "b")returns"a" - a literal
%must be written as%% - use
%n, not\n, when you want the platform line separator
MessageFormat
java.text.MessageFormat is a different formatting API with numbered {0} placeholders. It is mainly used for localized messages in resource bundles:
import java.text.MessageFormat;
System.out.println(MessageFormat.format(
"{0} has {1,number,integer} file(s), it''s {2,number,percent} full",
"Disk", 1234, 0.75));
// Disk has 1,234 file(s), it's 75% full
String pattern = "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.";
System.out.println(MessageFormat.format(pattern, 0)); // There are no files.
System.out.println(MessageFormat.format(pattern, 1)); // There is one file.
System.out.println(MessageFormat.format(pattern, 1500)); // There are 1,500 files.
Note that in MessageFormat a single quote starts a quoted section, so a literal apostrophe must be written as ''. MessageFormat.format uses the default locale; create a new MessageFormat(pattern, locale) to choose one.
Which one to use
"...".formatted(args): concise, for building a string with the default localeString.format(Locale, ...): when the output must not depend on the machine's localeSystem.out.printf: printing formatted output directlyFormatter: writing many formatted pieces into oneStringBuilder, file or streamMessageFormat: localized messages, plurals withchoice- plain concatenation or
StringBuilder: when no formatting (padding, precision etc.) is needed, they are simpler and faster