String.format and printf
String.format, printf and formatted() build text from a template with placeholders such as %d and %.2f, the same idea as printf in C. This page explains the specifier syntax and how Formatter applies it, runs every common conversion and flag, builds aligned tables, shows the locale and error traps, compares MessageFormat, and measures what formatting costs.
Contents
How format strings work
String.formatprintfformattedjava.util.Formatter%
%[argument_index$][flags][width][.precision]conversion
- The conversion is a letter that says how to show the argument:
for an integer,d for a decimal,f for any object.s - The width is the minimum number of characters; shorter results are padded with spaces, on the left unless the
flag is given.- - The precision is the number of digits after the point for
andf , and the maximum number of characters fore .s - Flags add signs, zero padding, grouping separators and alternate forms.
The template is parsed again on every call, and numbers are formatted using a Locale
| Conversion | Argument | Example | Result |
|---|---|---|---|
%d | Integer types, BigInteger | %05d | 00042 |
%f | floatdoubleBigDecimal | %.2f | 1234.57 |
%e%g%a | Floating point | %.3e | 1.235e+03 |
%x%X%o | Integer types | %X | FF |
%s%S | Anything (toString | %-6s | Ada |
%c | char | %c | B |
%b | Anything | %b | false |
%t | Dates and times | %tY | 2026 |
%n%% | None | Line separator, a literal % |
| API | Since | Best for |
|---|---|---|
String.formatPrintStream.printf | Java 5 | Most formatted text and console output |
"template".formatted(args) | Java 15 | Templates in text blocks |
Formatter | Java 5 | Writing formatted text into a StringBuilder |
MessageFormat | Java 1.1 | Translated messages with {0} |
NumberFormatDateTimeFormatter | Java 1.1, Java 8 | Numbers and dates for people; see |
String templates (STR."..."
The everyday specifiers
The values are a name, a small integer and a price with four decimals, so each line shows how one kind of specifier changes the same data.
import java.time.LocalDate;
public class Specifiers {
public static void main(String[] args) {
String name = "Ada";
int count = 42;
double price = 1234.5678;
System.out.println(String.format("%s has %d items", name, count));
System.out.println(String.format("%.2f | %10.2f | %-10.2f|", price, price, price));
System.out.println(String.format("%,d | %,.1f", 1234567, price));
System.out.println(String.format("%05d | %+d | %x | %X | %o", count, count, 255, 255, 8));
System.out.println(String.format("%e | %.3e", price, price));
System.out.println(String.format("%b | %c | %%", count > 40, 'Z'));
System.out.println(String.format("%10s|%-10s|", name, name));
System.out.println(String.format("%.4s", "abbreviation"));
// Reuse an argument by position, and %n for the platform line separator
System.out.printf("%1$s %1$s %2$s%n", "again", "done");
// Dates have their own conversions, but DateTimeFormatter is clearer
LocalDate day = LocalDate.of(2026, 11, 14);
System.out.println(String.format("%tY-%<tm-%<td (%<tA)", day));
// Java 15+: formatted() is String.format with the template first
System.out.println("%s scored %d%%".formatted(name, 97));
}
}
Output:
Ada has 42 items
1234.57 | 1234.57 | 1234.57 |
1,234,567 | 1,234.6
00042 | +42 | ff | FF | 10
1.234568e+03 | 1.235e+03
true | Z | %
Ada|Ada |
abbr
again again done
2026-11-14 (Saturday)
Ada scored 97%
rounds 1234.5678 to 1234.57.%.2f pads it to 10 characters on the left, and%10.2f on the right, which is what the%-10.2f marks show.| adds grouping separators,%,d pads with zeros, and%05d always shows the sign.%+d and%x print hex in lower and upper case, and%X of 8 is octal%o .10 uses scientific notation with 6 digits by default.%e prints a percent sign, and%% keeps only the first 4 characters,%.4s .abbr reuses the first argument, so%1$s appears twice.again ends the line with the platform's line separator.%n ,%tY and%tm format dates;%td reuses the previous argument.%< is clearer for anything beyond this.DateTimeFormatter (Java 15) is the same as"%s scored %d%%".formatted(...) with the template first.String.format
Flags, rounding and edge cases
The less common flags and conversions are where surprises hide. The values include halfway cases for rounding, a negative number that rounds to zero, null
public class FlagsAndEdge {
public static void main(String[] args) {
// %f rounds HALF_UP on the decimal value
for (double d : new double[] {0.5, 1.5, 2.5, 0.125, -0.4}) {
System.out.printf("%%.0f of %-6s -> %.0f %%.2f -> %.2f%n", d, d, d);
}
// Flags: - left, 0 zero-pad, + sign, space, ( negative in parentheses,
// , grouping, # alternate form
System.out.printf("[%8d] [%-8d] [%08d] [%+d] [% d] [%(d] [%,d]%n", 42, 42, 42, 42, 42, -42,
1234567);
System.out.printf("[%#x] [%#o] [%08.2f] [%-+8.1f]%n", 255, 8, -3.14159, 2.5);
// %g picks %e or %f, %a is hex floating point, %h is the hash code in hex
System.out.printf("%%g: %g %g %g %%a: %a %%h: %h%n", 0.00012345, 123.45, 1.2e10, 1.0,
"hi");
// %s calls toString, %S upper-cases, null prints "null"
Object nothing = null;
System.out.printf("%%s null: %s %%S: %S %%.4s: %.4s%n", nothing, "shout",
"abbreviation");
// %b is "true" for ANY non-null argument that is not a Boolean
System.out.printf("%%b: %b %b %b %b%n", true, null, "false", 0);
// %c takes a char or a code point
System.out.printf("%%c: %c %c %c%n", 'A', 66, 0x1D11E);
// Argument indexes and relative indexes
System.out.printf("%2$s %1$s %2$s | %s %<s %s%n", "a", "b");
}
}
Output:
%.0f of 0.5 -> 1 %.2f -> 0.50
%.0f of 1.5 -> 2 %.2f -> 1.50
%.0f of 2.5 -> 3 %.2f -> 2.50
%.0f of 0.125 -> 0 %.2f -> 0.13
%.0f of -0.4 -> -0 %.2f -> -0.40
[ 42] [42 ] [00000042] [+42] [ 42] [(42)] [1,234,567]
[0xff] [010] [-0003.14] [+2.5 ]
%g: 0.000123450 123.450 1.20000e+10 %a: 0x1.0p0 %h: d01
%s null: null %S: SHOUT %.4s: abbr
%b: true false true true
%c: A B 𝄞
b a b | a a b
rounds halves up, away from zero, using the decimal text of the%f : 0.5, 1.5 and 2.5 became 1, 2 and 3, and 0.125 became 0.13. This differs fromdouble for negative numbers and fromMath.round , which rounds half to even.DecimalFormat- -0.4 formatted with
gives%.0f . Reports that show-0 or-0 are usually fixed by adding-0.00 after rounding or by formatting a0.0 .BigDecimal - The space flag puts a space where a plus sign would go,
shows negatives in parentheses as accountants do, and( adds# or a leading0x for hex and octal.0 zero-pads after the sign:%08.2f .-0003.14 switches between plain and scientific notation depending on size,%g prints the exact binary value in hex (%a is 1.0), and0x1.0p0 prints the argument's%h in hex.hashCode prints%s for a null argument instead of throwing, andnull uppercases.%S is the trap: it prints%b only forfalse andnull . The stringBoolean.FALSE and the number 0 both print"false" .true accepts a code point, including the G clef U+1D11E. A plain%c (no index) after%s continues from the first argument again, and%2$s repeats the previous one, so the part after the bar prints the first argument twice and then the second.%<s
Aligned tables
Width and precision together make text tables for logs, command-line tools and reports. The data has one item name longer than its column, to show how to keep the layout intact.
import java.util.List;
public class Table {
record Item(String name, int qty, double price) {
}
public static void main(String[] args) {
List<Item> items = List.of(
new Item("Keyboard", 2, 49.99),
new Item("Monitor", 1, 189.0),
new Item("USB-C cable", 12, 7.5),
new Item("Extra-long HDMI cable", 3, 12.25));
String row = "%-12s %5s %10s%n";
System.out.printf(row, "Item", "Qty", "Total");
System.out.printf(row, "-".repeat(12), "-".repeat(5), "-".repeat(10));
double sum = 0;
for (Item it : items) {
double total = it.qty() * it.price();
sum += total;
// %-12.12s pads short names and truncates long ones, so columns stay aligned
System.out.printf("%-12.12s %5d %10.2f%n", it.name(), it.qty(), total);
}
System.out.printf("%-12s %5s %10.2f%n", "TOTAL", "", sum);
// Without the precision, a long value pushes the other columns out
System.out.printf("%-12s %5d %10.2f%n", items.get(3).name(), 3, 36.75);
// Width is counted in chars, not screen columns
System.out.printf("[%-6s] [%-6s]%n", "abc", "\u4E16\u754C");
// Width from a variable: build the format string
int width = 15;
System.out.printf("[%" + width + "s]%n", "right-aligned");
System.out.println("[" + " ".repeat(width - 6) + "padded" + "]");
}
}
Output:
Item Qty Total
------------ ----- ----------
Keyboard 2 99.98
Monitor 1 189.00
USB-C cable 12 90.00
Extra-long H 3 36.75
TOTAL 415.73
Extra-long HDMI cable 3 36.75
[abc ] [世界 ]
[ right-aligned]
[ padded]
- Keeping one row template,
, for the header and separator guarantees that they line up with the data rows. Text columns are left-aligned with"%-12s %5s %10s%n" , numbers right-aligned.- pads short names to 12 characters and cuts long ones to 12, so%-12.12s stays in its column. Without the precision, the long name pushed the rest of the line to the right.Extra-long H- Width counts
values, not screen columns. The two Chinese characters count as 2 but take 4 columns in most terminals, so the closing bracket is in a different place. Aligning East Asian text needs a width library.char - A width cannot be passed as an argument as in C's
; build it into the template, or pad with%*d ." ".repeat(n)
Locales: why machine output needs Locale.ROOT
Without an explicit locale, String.format
import java.util.Locale;
public class Locales {
public static void main(String[] args) {
double value = 9876.5;
System.out.println(String.format(Locale.US, "US: %,.2f", value));
System.out.println(String.format(Locale.GERMANY, "Germany: %,.2f", value));
Locale hindi = Locale.forLanguageTag("hi-IN-u-nu-deva");
System.out.println(String.format(hindi, "Hindi digits: %,.2f", value));
// The default locale is used when none is passed
Locale saved = Locale.getDefault(Locale.Category.FORMAT);
Locale.setDefault(Locale.Category.FORMAT, Locale.GERMANY);
String csv = String.format("%s,%.2f,%.2f", "widget", 1.5, 2.25);
System.out.println("CSV with German default: " + csv + " -> fields: "
+ csv.split(",").length);
String safe = String.format(Locale.ROOT, "%s,%.2f,%.2f", "widget", 1.5, 2.25);
System.out.println("CSV with Locale.ROOT: " + safe + " -> fields: "
+ safe.split(",").length);
System.out.println("String.valueOf ignores locale: " + 1.5);
Locale.setDefault(Locale.Category.FORMAT, saved);
}
}
Output:
US: 9,876.50
Germany: 9.876,50
Hindi digits: ९,८७६.५०
CSV with German default: widget,1,50,2,25 -> fields: 5
CSV with Locale.ROOT: widget,1.50,2.25 -> fields: 3
String.valueOf ignores locale: 1.5
- The US uses a comma for grouping and a dot for decimals, Germany the reverse. A locale with the
extension even switches to Devanagari digits.nu-deva - With a German default,
wrote%.2f , so the CSV line split into 5 fields instead of 3. The same code worked on a developer machine set to English.1,50 - Passing
gives neutral output that does not depend on the machine. Use it for files, logs that are parsed, URLs, JSON and SQL; use the user's locale for text people read.Locale.ROOT ,String.valueOf and concatenation never use a locale.Double.toString
Format errors
A mismatch between the template and the arguments is found only at run time. The program tries seven broken specifiers and shows which exception each one throws.
import java.util.IllegalFormatException;
public class Errors {
public static void main(String[] args) {
String[] formats = {"%d", "%s %s", "%q", "%.2d", "%-d", "%,s", "%5.2c"};
Object[][] arguments = {{"text"}, {"only one"}, {"x"}, {42}, {42}, {"x"}, {'x'}};
for (int i = 0; i < formats.length; i++) {
try {
String.format(formats[i], arguments[i]);
System.out.printf("%-8s ok%n", formats[i]);
} catch (IllegalFormatException e) {
System.out.printf("%-8s %s%n", formats[i], e.getClass().getSimpleName());
}
}
// Extra arguments are silently ignored
System.out.println("extra argument: " + String.format("%s", "a", "b"));
// %n is the platform line separator; \n is always a line feed
System.out.println("%n length: " + String.format("%n").length()
+ " on this OS, \\n length: " + "\n".length());
// A literal % must be doubled
System.out.println(String.format("progress: %d%%", 75));
try {
String.format("progress: %d%", 75);
} catch (IllegalFormatException e) {
System.out.println("single %: " + e.getClass().getSimpleName());
}
}
}
Output:
%d IllegalFormatConversionException
%s %s MissingFormatArgumentException
%q UnknownFormatConversionException
%.2d IllegalFormatPrecisionException
%-d MissingFormatWidthException
%,s FormatFlagsConversionMismatchException
%5.2c IllegalFormatPrecisionException
extra argument: a
%n length: 1 on this OS, \n length: 1
progress: 75%
single %: UnknownFormatConversionException
- All of these exceptions extend
, an unchecked exception. Passing aIllegalFormatException toString , giving too few arguments, an unknown conversion, a precision on an integer,%d without a width, and grouping on a string each have their own subclass.- - Extra arguments are silently ignored, so a forgotten placeholder does not fail; the value is just missing from the text.
is 1 character here because this is Linux; on Windows it is 2,%n . Use\r\n for console output and%n when the file format requires it.\n- A single
at the end throws% ; writeUnknownFormatConversionException .%%
IDEs and tools such as Error Prone check format strings at compile time, which catches most of these before they run.
MessageFormat, Formatter and text blocks
Other formatting tools fit cases that String.format
import java.text.MessageFormat;
import java.util.Formatter;
import java.util.Locale;
public class Alternatives {
public static void main(String[] args) {
String name = "Ada";
int files = 3;
// Java 15: formatted() puts the template first, handy with text blocks
String report = """
User: %s
Files: %d
""".formatted(name, files);
System.out.print(report);
// MessageFormat: numbered placeholders, reordering and plural choices
System.out.println(MessageFormat.format("{1} uploaded by {0}", name, "report.pdf"));
String pattern = "{0} has {1,choice,0#no files|1#one file|1<{1,number,integer} files}";
for (int n : new int[] {0, 1, 1200}) {
System.out.println(MessageFormat.format(pattern, name, n));
}
System.out.println(MessageFormat.format("It''s {0}", "fine") + " | "
+ MessageFormat.format("It's {0}", "broken"));
System.out.println(MessageFormat.format("{0}", 1234567) + " | "
+ MessageFormat.format("{0,number,#}", 1234567));
// Formatter writes into any Appendable, such as a StringBuilder
StringBuilder sb = new StringBuilder();
try (Formatter f = new Formatter(sb, Locale.ROOT)) {
for (int i = 1; i <= 3; i++) {
f.format("%d:%03d ", i, i * 7);
}
}
System.out.println("Formatter: " + sb);
}
}
Output:
User: Ada
Files: 3
report.pdf uploaded by Ada
Ada has no files
Ada has one file
Ada has 1,200 files
It's fine | Its {0}
1,234,567 | 1234567
Formatter: 1:007 2:014 3:021
on a text block keeps a multi-line template readable.formatted uses numbered placeholders, so a translation can putMessageFormat before{1} . The{0} format picks text by number, giving "no files", "one file" and "1,200 files".choice- In
, a single quote starts quoted text, soMessageFormat lost both the apostrophe and the placeholder. Write two quotes,It's {0} .It''s formats numbers with grouping by default, so an ID 1234567 becomesMessageFormat ;1,234,567 prints plain digits.{0,number,#}- A
writes into anyFormatter , here aAppendable , without creating an intermediate string per call.StringBuilder
What formatting costs
The program builds the same 500,000 lines with concatenation, a builder, String.formatformattedMessageFormatdouble
import java.text.MessageFormat;
import java.util.Locale;
import java.util.function.IntFunction;
public class FormatSpeed {
public static void main(String[] args) {
int n = 500000;
time("concatenation +", n, i -> "order " + i + " for " + "Ada" + ": " + (i % 100));
time("StringBuilder", n, i -> new StringBuilder().append("order ").append(i)
.append(" for ").append("Ada").append(": ").append(i % 100).toString());
time("String.format", n, i -> String.format("order %d for %s: %d", i, "Ada", i % 100));
time("String.format(ROOT)", n, i -> String.format(Locale.ROOT, "order %d for %s: %d", i,
"Ada", i % 100));
time("formatted()", n, i -> "order %d for %s: %d".formatted(i, "Ada", i % 100));
time("MessageFormat.format", n, i -> MessageFormat.format("order {0} for {1}: {2}",
String.valueOf(i), "Ada", String.valueOf(i % 100)));
time("%.2f via String.format", n, i -> String.format("%.2f", i / 7.0));
time("Double.toString", n, i -> Double.toString(i / 7.0));
}
// Best of 3 runs
static void time(String name, int n, IntFunction<String> f) {
long best = Long.MAX_VALUE;
long chars = 0;
for (int run = 0; run < 3; run++) {
chars = 0;
long t0 = System.nanoTime();
for (int i = 0; i < n; i++) {
chars += f.apply(i).length();
}
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf("%-24s %7.1f ms (%,d chars)%n", name, best / 1e6, chars);
}
}
Output (rough numbers, JDK 21 on 2 Linux CPUs):
concatenation + 15.9 ms (11,838,890 chars)
StringBuilder 10.1 ms (11,838,890 chars)
String.format 104.4 ms (11,838,890 chars)
String.format(ROOT) 88.0 ms (11,838,890 chars)
formatted() 87.2 ms (11,838,890 chars)
MessageFormat.format 197.3 ms (11,838,890 chars)
%.2f via String.format 161.7 ms (3,922,230 chars)
Double.toString 23.8 ms (7,942,266 chars)
- Concatenation with
and the+ were the fastest, with the lead between them changing from run to run, andStringBuilder was roughly four to nine times slower, because it parses the template and creates aString.format on every call.Formatter - Passing
or callingLocale.ROOT instead made no consistent difference; the three variants were within noise of each other.formatted was the slowest of the string builders, andMessageFormat.format was several times slower than%.2f , because decimal rounding goes through more general code.Double.toString
None of this matters for a message per request. In a loop that writes millions of lines, prefer concatenation or a StringBuilder
Which tool to use
| Situation | Use |
|---|---|
| A few values joined into a sentence | + |
| Fixed decimals, padding or alignment | String.formatprintf |
| Output read by programs | String.format(Locale.ROOT, ...) |
| Output read by people | String.format(userLocale, ...)NumberFormat |
| Multi-line template | A text block with formatted |
| Translated messages and plurals | MessageFormat'' |
| Many formatted pieces into one buffer | FormatterStringBuilder |
| Dates and times | DateTimeFormatter |
| Hot loops | Concatenation or StringBuilderString.format |