Course contentsShow
← Java
Lesson 2233 of 2,87043. String Handling in DepthFree lesson

Common Formatting Patterns and Pitfalls

Best practices for format strings, handling exceptions, and avoiding common formatting errors.

Common Formatting Patterns and Pitfalls

You'll learn best practices for writing reliable format strings and avoiding errors that trip up even experienced developers.

The Core Idea

String formatting is powerful but error-prone. Mismatched format specifiers, wrong argument counts, locale inconsistencies, and precision errors can all crash your program at runtime—not compile-time. Understanding common patterns and pitfalls helps you write defensive, maintainable formatting code.

Common Patterns to Follow

Match specifiers to argument types precisely. Always use %d for integers, %f for floats, %s for strings. Type mismatches throw IllegalFormatConversionException.

Use argument indexing for repeated values. Instead of passing the same variable twice, use %1$s to reuse argument 1: "User %1$s (ID: %1$s)".formatted(username).

Be explicit about precision. Don't write %.2f and assume it rounds—understand it truncates to two decimal places. Test edge cases.

Consider locale implications. Numbers formatted with String.format(Locale.US, "%.2f", price) use periods as decimal separators, while Locale.GERMANY uses commas. Hardcode locales when formatting for serialization or APIs.

Common Pitfalls to Avoid

Argument count mismatches. Forgetting an argument or passing extras throws MissingFormatArgumentException or is silently ignored. Always count your % placeholders.

Mixing 1-indexed positioning with sequential. You can't combine %1$s (indexed) and %s (sequential) in the same format string—pick one style.

Null arguments without handling. Passing null for %s prints "null" (usually fine), but %d with null crashes. Validate inputs or use %s as a safe default.

Forgetting escape sequences. To print a literal %, use %%. Forgetting this treats the next character as a format specifier.

Key Takeaway:
Always validate format strings against expected arguments, test with null and edge-case values, and be explicit about locale when formatting numbers—runtime formatting errors are preventable with careful pattern matching and defensive coding.