Table of Contents
Why Format Strings?
String formatting lets you create dynamic, readable text by injecting variables into placeholders. Use cases include:
- Generating log messages.
- Building user-friendly output (e.g., currency, dates).
- Structuring complex text (e.g., CSV/JSON).
1. String.format() vs System.out.printf()
Both methods use the same syntax but serve different purposes:
String.format()
: Returns a formattedString
.
String message = String.format("Hello, %s! You have %d messages.", "Radha", 5);
// "Hello, Radha! You have 5 messages."
System.out.printf()
: Directly prints formatted text to the console.
System.out.printf("Total: $%.2f%n", 19.99); // "Total: $19.99"
2. Common Format Specifiers
Specifier | Type | Example | Output |
---|---|---|---|
%s | String | String.format("%s", "Hi") | "Hi" |
%d | Integer | "%d" , 42 | "42" |
%f | Floating-point | "%.2f" , 3.1415 | "3.14" |
%tF | Date (ISO) | "%tF" , new Date() | "2024-05-05" |
%n | Newline | "Line1%nLine2" | "Line1\nLine2" |
%% | Literal % | "Discount: 10%%" | "Discount: 10%" |
Formatting Numbers
Control precision, padding, and commas:
// Precision:
String.format("PI: %.3f", Math.PI); // "PI: 3.142"
// Padding:
String.format("ID: %05d", 42); // "ID: 00042"
// Locale-Specific (e.g., commas):
String.format(Locale.US, "%,d", 1000000); // "1,000,000"
Formatting Dates
Use %t
specifiers with java.util.Date
:
Date now = new Date();
String.format("Date: %tF | Time: %tT", now, now);
// "Date: 2024-05-05 | Time: 14:30:45"
Key Date Specifiers:
%tF
: ISO date (yyyy-MM-dd
)%tT
: 24-hour time (HH:mm:ss
)%tD
: Short date (MM/dd/yy
)
3. Locale-Sensitive Formatting
Specify a Locale
to format numbers/dates regionally:
// German locale uses commas as decimal separators:
String.format(Locale.GERMAN, "%.2f", 3.14); // "3,14"
// US locale for currency:
String.format(Locale.US, "$%,.2f", 1000.5); // "$1,000.50"
Common Mistakes
❌ Mismatched Specifiers:
String.format("%d", "text"); // Throws IllegalFormatConversionException
❌ Missing Arguments:
String.format("Hello, %s and %s", "Radha"); // MissingSecondArgumentException
✅ Best Practices:
- Use
try-catch
for dynamic formats. - Prefer
DateTimeFormatter
for Java 8+ dates (Java DateTimeFormatter Example).
FAQ
How to format a String with multiple variables?
Use positional indexes (%1$s
):String.format("%1$s → %2$d → %1$s", "A", 10); // "A → 10 → A"
What’s the difference between %n
and \n
?
%n
is platform-independent (e.g., \r\n
on Windows), while \n
is Unix-only.
Up Next: String Performance & Optimization: Learn to optimize concatenation with StringBuilder
and avoid memory pitfalls.