String formatting

Core Java · lesson 26 of 42 · 3 min read

Build readable text with printf-style patterns instead of long chains of plus signs.

Open this lesson in the learning hub

Key points

  • String.format, System.out.printf and "...".formatted(...) all share one pattern language.
  • Specifiers: %s text, %d integer, %f decimal, %n newline, %% percent.
  • Width and precision align output: %-10s pads right, %5d pads left, %.2f keeps two decimals.
  • %,d groups thousands using the locale, so pass an explicit Locale whenever another program reads the output.
  • Specifiers must match the arguments in type and count, or you get an IllegalFormatException at runtime.
  • With no alignment or precision to worry about, plain concatenation is clearer. Reach for format when the shape matters.

Example

import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        System.out.printf("%s is %d years old%n", "Ada", 36);
        System.out.println(String.format("pi to 2dp: %.2f", Math.PI));
        System.out.println("formatted(): %s scored %d%%".formatted("Ada", 91));

        System.out.println(String.format("|%-10s|%5d|", "left", 42));
        System.out.println(String.format("|%10s|%-5d|", "right", 42));
        System.out.println(String.format("zero padded id: %05d", 42));

        System.out.println(String.format(Locale.US, "money: %,.2f", 1234567.891));
        System.out.println(String.format(Locale.GERMANY, "same value, de-DE: %,.2f", 1234567.891));

        System.out.println(String.format("hex %x, octal %o, sci %.2e", 255, 8, 12345.678));
        System.out.println(String.format("bool %b, char %c, percent %%", true, 'J'));
        System.out.println(String.format("reuse arg 1: %1$s and %1$s again", "echo"));
    }
}

One pattern plus its arguments beats a long chain of plus signs.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.