Code Snippets
/

Format Strings with String.format

Format Strings with String.format

`String.format` is Java's printf-style formatter for building human-readable strings without ad-hoc concatenation. This snippet covers the common conversions (`%s`, `%d`, `%.2f`, `%n`), padding and alignment for table layouts, and locale-aware vs locale-independent formatting. Reach for `String.format` for any output that mixes types or needs precise width control.

Java
Easy
3 snippets
strings
string-manipulation
java-string-builder

299 views

8

import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String name = "Ada";
        int level = 7;
        double balance = 1234.5;

        // %s string, %d integer, %f float, %n platform line separator
        String msg = String.format("%s is level %d with balance %.2f%n", name, level, balance);
        System.out.print(msg);

        // printf is the same formatter going straight to stdout
        System.out.printf("hex=%x bin=%s oct=%o%n", 255, Integer.toBinaryString(5), 8);
    }
}

The format string contains conversion specifiers introduced by %. %s is the most general, calling toString() on whatever you pass. %d requires an integer, %f a floating-point number with optional precision (%.2f for two decimals), and %n emits the platform-correct line separator (use it instead of \n for portable output). String.format returns a String; System.out.printf writes directly to stdout using the same syntax.