Java String Formatting — format(), printf() & Text Blocks

2 minute read

Java provides several ways to format strings — from classic printf()-style format specifiers to modern text blocks. This chapter covers them all.


String.format()

Creates a formatted string without printing it:

String msg = String.format("Hello, %s! You are %d years old.", "Alice", 30);
// "Hello, Alice! You are 30 years old."

Common Format Specifiers

Specifier Type Example Output
%s String format("%s", "Hi") Hi
%d Integer format("%d", 42) 42
%f Float/Double format("%f", 3.14) 3.140000
%.2f Float (2 decimal) format("%.2f", 3.14159) 3.14
%b Boolean format("%b", true) true
%c Character format("%c", 'A') A
%n Newline (platform) format("line1%nline2") line1↵line2
%x Hex format("%x", 255) ff
%o Octal format("%o", 8) 10
%% Literal % format("100%%") 100%

printf() — Print Formatted

Same format specifiers, but prints directly to console:

System.out.printf("Name: %s, Score: %d%n", "Bob", 95);
// Name: Bob, Score: 95

Width, Padding, and Alignment

Right-Aligned (Default)

System.out.printf("|%10s|%n", "Java");
// |      Java|

Left-Aligned

System.out.printf("|%-10s|%n", "Java");
// |Java      |

Zero-Padded Numbers

System.out.printf("|%010d|%n", 42);
// |0000000042|

Practical Table Formatting

System.out.printf("%-15s %5s %10s%n", "Product", "Qty", "Price");
System.out.printf("%-15s %5d %10.2f%n", "Widget", 100, 9.99);
System.out.printf("%-15s %5d %10.2f%n", "Gadget", 50, 24.95);
System.out.printf("%-15s %5d %10.2f%n", "Doohickey", 200, 1.50);

Output:

Product           Qty      Price
Widget            100       9.99
Gadget             50      24.95
Doohickey         200       1.50

Argument Index

Reference arguments by position (1-indexed):

String.format("%1$s has %2$d cats and %2$d dogs", "Alice", 3);
// "Alice has 3 cats and 3 dogs"

Formatting Dates

import java.time.LocalDateTime;

LocalDateTime now = LocalDateTime.now();

System.out.printf("Date: %tF%n", now);    // 2026-04-20
System.out.printf("Time: %tT%n", now);    // 14:30:45
System.out.printf("Day:  %tA%n", now);    // Monday
System.out.printf("Full: %tc%n", now);    // Mon Apr 20 14:30:45 ...
Specifier Meaning Example
%tF ISO date 2026-04-20
%tT 24h time 14:30:45
%tD US date 04/20/26
%tA Day name Monday
%tB Month name April

Tip: For serious date formatting, use DateTimeFormatter (covered in the Dates & Time chapter).


formatted() — Java 15+

Instance method on String:

String msg = "Hello, %s! You scored %d%%".formatted("Alice", 95);
// "Hello, Alice! You scored 95%"

Equivalent to String.format() but reads more fluently.


Text Blocks — Java 13+ (Standard in 15)

Multi-line strings without escape characters:

String json = """
        {
            "name": "Alice",
            "age": 30,
            "city": "New York"
        }
        """;

Rules

  1. Opening """ must be followed by a newline.
  2. Closing """ position determines indentation stripping.
  3. Common leading whitespace is removed automatically.

Text Blocks with Format

String html = """
        <html>
            <body>
                <h1>%s</h1>
                <p>Score: %d</p>
            </body>
        </html>
        """.formatted("Alice", 95);

Escape Sequences in Text Blocks

Escape Meaning
\n Newline
\s Space (prevents trailing space stripping)
\ at end of line Line continuation (no newline)
String single = """
        This is a very long \
        line that continues.""";
// "This is a very long line that continues."

MessageFormat (Localisation)

import java.text.MessageFormat;

String msg = MessageFormat.format(
    "On {0,date}, {1} scored {2,number,integer} points.",
    new java.util.Date(), "Alice", 42
);

Useful for internationalised applications.


Common Mistakes

Mistake Problem Fix
Using \n instead of %n Not platform-independent Use %n in format strings
Wrong specifier type IllegalFormatConversionException Match %d with int, %s with String
Forgetting %% for literal % MissingFormatArgumentException Use %%
Text block indentation Unexpected leading spaces Align closing """

Key Takeaways

  1. String.format() and printf() use the same format specifiers (%s, %d, %f, etc.).
  2. Control width, alignment, and padding: %-10s (left), %010d (zero-padded).
  3. Use %n for platform-independent newlines.
  4. Text blocks (Java 13+) simplify multi-line strings — great for JSON, SQL, HTML.
  5. Use .formatted() (Java 15+) for a fluent alternative to String.format().

What’s Next?

Next: Regular Expressions — pattern matching, the Pattern and Matcher classes, and common regex patterns.

Updated: