Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Formatted Method: String.format, Formatter, and String.formatted

Learn how to format strings in Java with String.format, Formatter, and String.formatted, including format specifiers, locale-aware output, and common pitfalls.

~5 min readJava
#String.format#Java Formatter#printf#String formatting
Illustration of a Java string template with placeholders being filled by values, representing the formatted method.

When you need to combine static text with dynamic values, Java's formatting APIs—String.format, the Formatter class, and, since Java 15, the String.formatted instance method—are often the clearest option. Instead of concatenating fragments with +, you define a template and supply the values that fill it. This keeps the output structure visible in one place and reduces the risk of missing spaces or misordered parts.

The Core Syntax of the Format Method

String.format is a static method that returns a formatted string. Its first argument is the format string, and the remaining arguments are the values to insert. The Formatter class provides the same capability through an instance, which is useful when you need to write formatted output to an Appendable such as a StringBuilder or a file.

java
String name = "Ada"; int year = 1843; String message = String.format("%s published the first algorithm in %d.", name, year);

The format string contains plain text and format specifiers. Each specifier starts with % and describes how to render one argument. The %s specifier converts the argument to a string, and %d formats an integer as a decimal value. The result is a single string with the placeholders replaced.

On Java 15 and later, String.formatted(Object... args) is an instance method that uses the same format specifiers, so the previous example can also be written as:

java
String message = "%s published the first algorithm in %d.".formatted(name, year);

The same behavior is available through Formatter:

java
StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); formatter.format("Value: %.2f", 3.14159); System.out.println(sb.toString()); // Value: 3.14

The Formatter constructor accepts an Appendable, so you can direct the output to a StringBuilder, a PrintStream, or any other destination. This is particularly useful when you want to build a large string incrementally without creating intermediate strings.

Format Specifiers and Argument Indexing

Each format specifier describes the type of the argument and the output style. Common specifiers include %s for strings, %d for integers, %f for floating-point values, %x for hexadecimal, and %t for date/time values. You can add flags, width, and precision between the % and the conversion character.

java
System.out.printf("%-10s %5d%n", "ID", 42);

Here %-10s left-aligns the string in a 10-character field, and %5d right-aligns the integer in a 5-character field. The %n specifier produces a platform-specific line separator.

When a format string uses the same argument more than once, you can reference it by index. The index is a number followed by $ immediately after the %.

java
String result = String.format("%1$s has %2$d books. %1$s reads daily.", "Lin", 7);

The %1$s refers to the first argument ("Lin"), and %2$d refers to the second argument (7). This avoids duplicating the argument list and keeps the mapping explicit when the order of references differs from the argument order.

Locale-Aware Formatting

By default, String.format uses the default locale of the JVM. That affects the decimal separator, grouping characters, and the names of months and days. When you need consistent output regardless of the system locale, pass a Locale as the first argument.

java
String us = String.format(Locale.US, "%,.2f", 12345.678); // 12,345.68 String de = String.format(Locale.GERMANY, "%,.2f", 12345.678); // 12.345,68

If you are generating output for a specific audience, always supply the intended Locale explicitly. Relying on the default locale can produce different results on different servers or user machines, which is a common source of subtle bugs in internationalized applications.

Performance Costs of Repeated Formatting

Constructing a Formatter and parsing a format string has a small cost on every format call, so formatting inside a hot loop can add overhead. If you are repeatedly writing into the same destination, reuse a single Formatter and clear the buffer between writes.

java
StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb); for (int i = 0; i < 1000; i++) { sb.setLength(0); formatter.format("Item %d: %s%n", i, items[i]); // consume sb.toString() } formatter.close();

Calling setLength(0) on the StringBuilder clears the previous output without allocating a new buffer. The Formatter still parses the format string on every call, but reuse avoids constructing a new object each time.

For extremely high-throughput string building, a StringBuilder with manual append calls may be faster because it avoids format parsing entirely. The tradeoff is readability and maintainability. Measure your specific use case before optimizing; in most application code, the formatting cost is negligible compared to I/O or database access.

Common Formatting Mistakes and How to Avoid Them

The most frequent error is providing the wrong number or type of arguments. String.format throws IllegalFormatConversionException if the specifier does not match the argument type, and MissingFormatArgumentException if an argument is missing. The exception message usually identifies the offending specifier, but it can be cryptic when the format string is long.

Another common mistake is confusing width with precision. For floating-point numbers, %.2f means two digits after the decimal point, while %8.2f means a total field width of eight characters with two decimal digits. The width includes the decimal point and any sign, so a negative number may require more space than expected.

Null handling can also surprise you. %s renders a null reference as the string "null", and numeric conversions in standard Java format null as "null" as well. If you need a different display value, check the argument before formatting.

java
String value = (name != null) ? name : "unknown"; String out = String.format("User: %s", value);

Also be careful with the %n specifier. It is the correct way to insert a line break in a format string; using \n works on most platforms but is not portable. %n always produces the platform-specific separator.

Choosing Between String.format and Other Approaches

String.format is not the only way to build strings in Java. StringBuilder with manual appends gives you full control and avoids format parsing, but the code becomes verbose when the template has many placeholders. MessageFormat is designed for human-readable messages and supports argument indexing and choice-based plural rules, but its syntax is more complex, and it is not a drop-in replacement for String.format.

The following table summarizes the tradeoffs:

ApproachReadabilityPerformanceUse case
String.formatHighModerateFixed templates with few values
StringBuilderLowHighLoops or performance-critical paths
MessageFormatMediumLowInternationalized messages with placeholders

Use String.format when the format string is stable and the number of arguments is small. Use StringBuilder when you are concatenating many pieces in a loop and the structure is simple. Use MessageFormat when you need locale-sensitive plural rules and indexed placeholders in a resource bundle.

Formatting Dates and Times

The %t specifier in String.format can format date/time values such as Date, Calendar, Long, and TemporalAccessor implementations like LocalDateTime, but the required prefixes and flags are easy to misread. For readable, thread-safe date/time formatting, prefer java.time.format.DateTimeFormatter.

java
LocalDateTime now = LocalDateTime.now(); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); String formatted = now.format(fmt);

If you need to mix a date/time value with other String.format arguments, %t can format a LocalDateTime directly. For most new code, however, keeping date/time formatting separate from general string formatting is clearer and avoids combining two different formatting systems.

Java's formatting APIs are practical tools for building readable output, but they are not a universal solution. Knowing when to use String.format, when to reuse a Formatter, and when to reach for a dedicated class like DateTimeFormatter keeps your code maintainable and avoids surprising runtime errors.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.