13. Modern String Formatting
Java offers String.format(), String.formatted() (Java 15+), printf, and MessageFormat for string formatting; use %n for platform-neutral newlines and know the common format specifiers.
Explanation
String.format(fmt, args...) is the classic static approach. Java 15 added String::formatted as an instance method for more fluent chaining: "Hello %s".formatted("World").
Common format specifiers: %s (toString), %d (decimal integer), %f (floating point, default 6 decimal places), %.2f (2 decimal places), %n (platform newline โ prefer over \n for portability in cross-platform output), %x (hex), %05d (zero-padded width 5), %-10s (left-aligned in width 10).
MessageFormat (from java.text) uses {0}, {1} indexed placeholders and supports locale-aware number/date formatting. For complex localisation use MessageFormat; for simple string building prefer String.formatted() or text blocks with formatted().
Example
import java.text.MessageFormat;
public class StringFormattingDemo {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
double score = 98.567;
// String.format โ classic static
String s1 = String.format("Name: %-10s Age: %3d Score: %.2f", name, age, score);
System.out.println(s1); // Name: Alice Age: 30 Score: 98.57
// String::formatted โ fluent instance method (Java 15+)
String s2 = "Hello, %s! You scored %.1f%%".formatted(name, score);
System.out.println(s2); // Hello, Alice! You scored 98.6%
// %n vs \n: %n is platform-neutral newline
System.out.printf("Line 1%nLine 2%n");
// Hex and zero-padding
int value = 255;
System.out.printf("Dec: %d Hex: %#x Padded: %08d%n", value, value, value);
// Dec: 255 Hex: 0xff Padded: 00000255
// MessageFormat for localisation/indexed args
String pattern = "User {0} has {1} messages.";
String msg = MessageFormat.format(pattern, name, 5);
System.out.println(msg); // User Alice has 5 messages.
// Text block + formatted (clean for multi-line templates)
String report = """
Name: %s
Age: %d
Score: %.2f
""".formatted(name, age, score);
System.out.print(report);
}
}Sources
- https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html#formatted(java.lang.Object...) โ String.formatted
- https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Formatter.html โ Format specifiers reference