Java String.format() method Usage Java String.format() method Usage

Page content

This article demonstrate use of String.format() in Java with many examples…

The String.format() method is used to produce formatted string, numeric, and date/time data, and locale specific output. It requires a format string and argument list as input.

1. Syntax

//Returns a formatted string using the specified format string and arguments.
static String format(String format, Object... args)	

//Returns a formatted string using the specified locale, format string, and arguments.
static String format(Locale l, String format, Object... args)	

Let’s look into format specifier before we look into examples

Syntax of format specifier
%[argument_index$][flags][width][.precision]conversion

Where,

  • optional argument_index is position of argument. The first arg is referenced by 1$, the second by 2$, etc.
  • optional flags is set of characters to modify the output format
    If not specified - The result will include a leading space for positive values
    - The result will be left-justified.
    # The result should use a conversion-dependent alternate form
    + The result will always include a sign
    0 The result will be zero-padded
    , The result will include locale-specific grouping separators
    ( The result will enclose negative numbers in parentheses
  • optional width is minimum number of characters in string output
  • optional precision is used for floating numbers to indicate numbers after decimal places.
  • required conversion is character indicating how it should be formatted
    s or S for string
    f for floating point numbers
    d for integers
    t for date and time
    n for line break

2. String Format Examples

2.1 String Template

String[] fruits = new String[] {"Mango", "Grapes", "Banana", "Kiwi"};

// String Concat
System.out.println(String.format("My favourite fruits are %1$s, %2$s, %3$s and %4$s", fruits));

//Reverse String Concat
System.out.println(String.format("My favourite fruits are %4$s, %3$s, %2$s and %1$s", fruits));

We have used formatter %1$s, %2$s, %3$s, %4$s to specify the position of string arguments and %n for line break.

Output
My favourite fruits are Mango, Grapes, Banana and Kiwi My favourite fruits are Kiwi, Banana, Grapes and Mango

2.2 String Line Break

String format can be used to create multi line string in Java

System.out.println(String.format("Address:-%nUnit 505,%n32 Cross Street", null));
Output
Address:- Unit 505, 32 Cross Street

2.3 String Padding

Following String format will add left padding of 10 characters to foo
%13s says that output will have min width of 13 including foo length, which is 3 hence (13 - 3 =) 10 left padding space.

System.out.println(String.format("%13s", "foo"));
Output
foo

3. Number Format Examples

3.1 Float Decimal Places

System.out.println(Math.PI);

// Rounding off Decimal Places      
System.out.println(String.format("%.1f", Math.PI));
System.out.println(String.format("%.5f", Math.PI));
System.out.println(String.format("%.10f", Math.PI));

We have used formatter %.1f, %.5f, and %.10f to show 1, 5 and 10 decimal places of PI respectively.

Output
3.141592653589793 3.1 3.14159 3.1415926536

3.2 Float Padding

// Min Width with leading spaces
System.out.println(String.format("%10f", Math.PI));
System.out.println(String.format("%20f", Math.PI));
System.out.println(String.format("%30f", Math.PI));

We have used formatter %10f, %20f, and %30f to show minimum 10, 20 and, 30 characters with leading space respectively. We see that string length 2.141593 is 8 characters which result in padding of 2, 12 and, 22 characters respectively.

Output
3.141593 3.141593 3.141593

3.3 Negative Floating Point Numbers

// +ve Floating Numbers
System.out.println(String.format("%+20.5f", Math.PI));     // + Flag show sign
System.out.println(String.format("%020.5f", Math.PI));     // 0 Flag for leading zeros
System.out.println(String.format("%(20.5f", Math.PI));    // ( Flag to show -ve numbers in parentheses

// -ve Floating Numbers
System.out.println(String.format("%+20.5f", -Math.PI));
System.out.println(String.format("%020.5f", -Math.PI));
System.out.println(String.format("%(20.5f", -Math.PI)); 
Output
+3.14159 00000000000003.14159 3.14159 -3.14159 -0000000000003.14159 (3.14159)

3.4 Float with locale

//Locale Specific
System.out.println(String.format(Locale.FRANCE, "%f", Math.PI));
System.out.println(String.format(Locale.FRANCE, "%f", -Math.PI));  
Output
3,141593 -3,141593

3.5 Format Number with Commas

System.out.println(String.format("%,d", 1234567890));
Output
1,234,567,890

4. Date Format Examples

4.1 LocalDateTime Format

LocalDateTime date = LocalDateTime.parse("1986-08-22T05:45:59");

System.out.println(String.format("My Birth Date is %1$te-%1$tm-%1$tY %1tT", date));
System.out.println(String.format("I was born on %1$teth %1tB, %1$tY", date));
Output
My Birth Date is 22-08-1986 05:45:59 I was born on 22th August, 1986

4.2 LocalDate Format

Format LocalDate to yyyymmdd

LocalDate date = LocalDate.parse("2020-12-25");
// yyyymmdd
System.out.println(String.format("%1$tY%1$tm%1$te", date));
Output
20201225

5. Print Format Examples

5.1 System.out.printf and System.out.format

If you have to just print formatted output and doesn’t require returned output as string, you can use System.out.printf or System.out.format instead.

String print = "Hello World !!!";

System.out.println(String.format("Saying - %s", print));

System.out.printf("Saying - %s", print);

System.out.format("Saying - %s", print);

All the three System.out print the same output

Output
Saying - Hello World !!! Saying - Hello World !!! Saying - Hello World !!!

6. Gotchas

String.format() looks harmless, but a few mistakes only surface at runtime — the compiler can’t check your format string against your arguments, so these all pass compilation and blow up when the line actually executes.

6.1 MissingFormatArgumentException

If your format string references an argument index (or has more %s/%d placeholders) than you actually pass in, you get a MissingFormatArgumentException, not a silently blank value.

System.out.println(String.format("Hello %s, you are %s years old", "Sam"));
Output
Exception in thread "main" java.util.MissingFormatArgumentException: Format specifier '%s' at java.base/java.util.Formatter.format(Formatter.java:2790) at java.base/java.util.Formatter.format(Formatter.java:2728) at java.base/java.lang.String.format(String.java:4379)

Here we have two %s placeholders but only one argument ("Sam"), so the second placeholder has nothing to bind to. This is easy to hit when a format string is edited (a placeholder added or reordered) without updating the argument list to match.

6.2 IllegalFormatConversionException

Each conversion character expects a specific argument type — %d for integral numbers, %f for floating point, %s for basically anything. Pass an argument of the wrong type and you get an IllegalFormatConversionException.

String name = "Sam";
System.out.println(String.format("Age: %d", name));
Output
Exception in thread "main" java.util.IllegalFormatConversionException: d != java.lang.String at java.base/java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4515) at java.base/java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:3066) at java.base/java.util.Formatter$FormatSpecifier.print(Formatter.java:3021) at java.base/java.util.Formatter.format(Formatter.java:2791) at java.base/java.util.Formatter.format(Formatter.java:2728) at java.base/java.lang.String.format(String.java:4379)

%d only works with Integer, Long, Short, Byte (and their primitive equivalents) — not String, and notably not Double/Float either, since those need %f. If the value is coming from user input or a method that could return null/unexpected types, validate or convert it before formatting rather than letting the exception surface.

6.3 The .formatted() instance method (Java 15+)

Since Java 15, String has an instance method formatted(Object... args) that does the same job as String.format(), just called on the format string itself instead of passed to a static method:

String name = "Sam";
int age = 30;

String s1 = String.format("%s is %d years old", name, age);
String s2 = "%s is %d years old".formatted(name, age);

System.out.println(s1.equals(s2)); // true — same result
Output
true

Functionally they’re identical — formatted() is really just a convenience wrapper around String.format(). It’s worth reaching for when the format string is the more natural starting point in the expression, especially with Java 15+ text blocks:

String message = """
    Name: %s
    Age: %d
    """.formatted(name, age);

It reads left-to-right (string, then how to fill it in) rather than static-method-first, which some find easier to follow — but it’s purely a style choice, not a performance or capability difference.

6.4 Performance in loops

String.format() parses the format string (splitting it into literal text and conversion specifiers) on every single call — there’s no caching of a previously-seen format string. That parsing overhead is negligible for one-off calls like logging a single line, but it adds up fast inside a loop that builds output for large datasets.

In a quick local test formatting a row of output 1,000,000 times, String.format() took over 15x longer than building the equivalent string with StringBuilder:

long start1 = System.nanoTime();
StringBuilder sink1 = new StringBuilder();
for (int i = 0; i < 1_000_000; i++) {
    sink1.append(String.format("Row %d: %s", i, "value"));
}
long end1 = System.nanoTime();

long start2 = System.nanoTime();
StringBuilder sink2 = new StringBuilder();
for (int i = 0; i < 1_000_000; i++) {
    sink2.append("Row ").append(i).append(": ").append("value");
}
long end2 = System.nanoTime();
Output
String.format loop: 438 ms StringBuilder loop: 25 ms Ratio: 17.5x

Exact numbers will vary by JVM and hardware, but the gap is consistently large because String.format() does regex-like parsing and boxing/unboxing of primitive arguments on every call. If you’re formatting inside a hot loop — building a large CSV/log file line by line, for example — prefer plain concatenation or StringBuilder.append(), and reserve String.format() for occasional, human-facing output where readability matters more than raw speed.