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.format, printf and formatted all hand the work to java.util.Formatter, added in Java 5. It scans the template, copies plain text through, and replaces each format specifier with one argument converted to text. A specifier has this shape, where only the % and the conversion are required:

%[argument_index$][flags][width][.precision]conversion

  • The conversion is a letter that says how to show the argument: d for an integer, f for a decimal, s for any object.
  • 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 f and e, and the maximum number of characters for 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, by default the JVM's format locale. Both facts matter, for speed and for correctness.

The common conversions
ConversionArgumentExampleResult
%dInteger types, BigInteger%05d of 4200042
%ffloat, double, BigDecimal%.2f of 1234.56781234.57
%e, %g, %aFloating point%.3e of 1234.56781.235e+03
%x, %X, %oInteger types%X of 255FF
%s, %SAnything (toString)%-6s of "Ada"Ada
%cchar or code point%c of 66B
%bAnything%b of nullfalse
%t...Dates and times%tY2026
%n, %%NoneLine separator, a literal %
Formatting APIs
APISinceBest for
String.format, PrintStream.printfJava 5Most formatted text and console output
"template".formatted(args)Java 15Templates in text blocks
FormatterJava 5Writing formatted text into a StringBuilder or file
MessageFormatJava 1.1Translated messages with {0} placeholders and plurals
NumberFormat, DateTimeFormatterJava 1.1, Java 8Numbers and dates for people; see numbers and strings

String templates (STR."...") were a preview feature in Java 21 and 22 (JEPs 430 and 459); the next proposal, JEP 465, was withdrawn, so they are not covered here. The programs were compiled and run on JDK 21.

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.

Java
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:

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%
  • %.2f rounds 1234.5678 to 1234.57. %10.2f pads it to 10 characters on the left, and %-10.2f on the right, which is what the | marks show.
  • %,d adds grouping separators, %05d pads with zeros, and %+d always shows the sign. %x and %X print hex in lower and upper case, and %o of 8 is octal 10.
  • %e uses scientific notation with 6 digits by default. %% prints a percent sign, and %.4s keeps only the first 4 characters, abbr.
  • %1$s reuses the first argument, so again appears twice. %n ends the line with the platform's line separator.
  • %tY, %tm and %td format dates; %< reuses the previous argument. DateTimeFormatter is clearer for anything beyond this.
  • "%s scored %d%%".formatted(...) (Java 15) is the same as String.format with the template first.

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, and a code point outside the BMP.

Java
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:

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
  • %f rounds halves up, away from zero, using the decimal text of the double: 0.5, 1.5 and 2.5 became 1, 2 and 3, and 0.125 became 0.13. This differs from Math.round for negative numbers and from DecimalFormat, which rounds half to even.
  • -0.4 formatted with %.0f gives -0. Reports that show -0 or -0.00 are usually fixed by adding 0.0 after rounding or by formatting a BigDecimal.
  • The space flag puts a space where a plus sign would go, ( shows negatives in parentheses as accountants do, and # adds 0x or a leading 0 for hex and octal. %08.2f zero-pads after the sign: -0003.14.
  • %g switches between plain and scientific notation depending on size, %a prints the exact binary value in hex (0x1.0p0 is 1.0), and %h prints the argument's hashCode in hex.
  • %s prints null for a null argument instead of throwing, and %S uppercases.
  • %b is the trap: it prints false only for null and Boolean.FALSE. The string "false" and the number 0 both print true.
  • %c accepts a code point, including the G clef U+1D11E. A plain %s (no index) after %2$s continues from the first argument again, and %<s repeats the previous one, so the part after the bar prints the first argument twice and then the second.

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.

Java
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:

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, "%-12s %5s %10s%n", for the header and separator guarantees that they line up with the data rows. Text columns are left-aligned with -, numbers right-aligned.
  • %-12.12s pads short names to 12 characters and cuts long ones to 12, so Extra-long H stays in its column. Without the precision, the long name pushed the rest of the line to the right.
  • Width counts char 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.
  • A width cannot be passed as an argument as in C's %*d; build it into the template, or pad with " ".repeat(n).

Locales: why machine output needs Locale.ROOT

Without an explicit locale, String.format uses the default format locale, which comes from the operating system. The program formats one number in three locales and then writes a CSV line with a German default, a common production bug.

Java
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:

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 nu-deva extension even switches to Devanagari digits.
  • With a German default, %.2f wrote 1,50, so the CSV line split into 5 fields instead of 3. The same code worked on a developer machine set to English.
  • Passing Locale.ROOT 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.
  • String.valueOf, Double.toString and concatenation never use a locale.

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.

Java
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:

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 IllegalFormatException, an unchecked exception. Passing a String to %d, giving too few arguments, an unknown conversion, a precision on an integer, - 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.
  • %n is 1 character here because this is Linux; on Windows it is 2, \r\n. Use %n for console output and \n when the file format requires it.
  • A single % at the end throws UnknownFormatConversionException; write %%.

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 handles badly: translated messages where word order changes, plural forms, and writing many formatted pieces into one buffer.

Java
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:

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
  • formatted on a text block keeps a multi-line template readable.
  • MessageFormat uses numbered placeholders, so a translation can put {1} before {0}. The choice format picks text by number, giving "no files", "one file" and "1,200 files".
  • In MessageFormat, a single quote starts quoted text, so It's {0} lost both the apostrophe and the placeholder. Write two quotes, It''s.
  • MessageFormat formats numbers with grouping by default, so an ID 1234567 becomes 1,234,567; {0,number,#} prints plain digits.
  • A Formatter writes into any Appendable, here a StringBuilder, without creating an intermediate string per call.

What formatting costs

The program builds the same 500,000 lines with concatenation, a builder, String.format, formatted and MessageFormat, then formats a double two ways. The fastest of three runs is reported for every approach.

Java
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):

Output
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 StringBuilder were the fastest, with the lead between them changing from run to run, and String.format was roughly four to nine times slower, because it parses the template and creates a Formatter on every call.
  • Passing Locale.ROOT or calling formatted instead made no consistent difference; the three variants were within noise of each other.
  • MessageFormat.format was the slowest of the string builders, and %.2f was several times slower than Double.toString, because decimal rounding goes through more general code.

None of this matters for a message per request. In a loop that writes millions of lines, prefer concatenation or a StringBuilder, and format numbers with simpler methods.

Which tool to use

Choosing a formatting tool
SituationUse
A few values joined into a sentence+ concatenation
Fixed decimals, padding or alignmentString.format or printf
Output read by programsString.format(Locale.ROOT, ...)
Output read by peopleString.format(userLocale, ...) or NumberFormat
Multi-line templateA text block with formatted
Translated messages and pluralsMessageFormat, with '' for apostrophes
Many formatted pieces into one bufferFormatter over a StringBuilder
Dates and timesDateTimeFormatter
Hot loopsConcatenation or StringBuilder, not String.format