Cheatsheet: Java String.format

Basic Syntax

The `String.format` method formats strings using placeholders. Placeholders start with `%` and are followed by format specifiers.

String result = String.format("Hello, %s!", "World"); // Hello, World!

Multiple placeholders can be used, and arguments are matched in the same order they appear.

String result = String.format("%s is %d years old.", "Alice", 25); // Alice is 25 years old.

Handling Duplicated Arguments

Using the same argument multiple times by repeating it in the argument list.

String result = String.format("%s %s %s %s %s %s", "hello", "hello", "hello", "hello", "hello", "hello"); 
// hello hello hello hello hello hello

Using positional indexing to refer to the same argument multiple times.

String result = String.format("%1$s %1$s %1$s %1$s %1$s %1$s", "hello"); 
// hello hello hello hello hello hello

Using the `<` symbol to reuse the last argument without repeating it.

String result = String.format("%s %<s %<s %<s", "hello"); 
// hello hello hello hello

Format Specifiers

Common format specifiers include `%s` for strings, `%d` for integers, and `%f` for floating-point numbers.

String result = String.format("Name: %s, Age: %d, Height: %.2f", "John", 30, 5.75); 
// Name: John, Age: 30, Height: 5.75

Formatting numbers with leading zeros.

String result = String.format("Order ID: %05d", 42); 
// Order ID: 00042

Specifying width and alignment for strings.

String result = String.format("|%-10s|%10s|", "left", "right"); 
// |left      |     right|

Advanced Formatting Techniques

Using `%%` to include a literal `%` in the formatted string.

String result = String.format("Discount: 50%% off!"); 
// Discount: 50% off!

Combining argument indexing and format specifiers.

String result = String.format("%2$s is %1$d years old.", 30, "John"); 
// John is 30 years old.

Using locale for formatting (e.g., currency or date).

String result = String.format(Locale.US, "Price: $%,.2f", 12345.678); 
// Price: $12,345.68