String.format() in Java
Fast recall
Quick revision
Core answer
String.format(format, args...) returns text using Formatter syntax such as %s, %d, %.2f, and %n. The no-locale overload uses the default formatting locale, so use String.format(Locale.ROOT, ...) or a chosen locale when output must be stable. In logging frameworks, prefer their placeholder API instead of eagerly formatting a message.Whether you know the format specifier syntax and can use String.format() for readable output construction.
Using + concatenation for multi-value messages when String.format() would be clearer. Also mixing up %s (any object, calls toString) and %d (must be integer — throws exception for String).
Mention that Java 15 introduced text blocks (triple-quoted strings) as an alternative for multi-line templates, and that printf() is String.format() but printed directly to System.out.
Interview-ready guide
Interview answer
I reach for String.format() whenever a message has several moving parts and + concatenation would turn into an unreadable chain. You write the sentence once with placeholders and pass the values in order — String.format("User %s logged in from %s", name, ip) reads far better than gluing five fragments together, and it's much easier to change later.
The placeholders worth knowing: %s for any object — it just calls toString(), so it's the safe one; %d strictly for integers; and %.2f for a double rounded to two places, which I use for money and scores. One real gotcha is that %d is checked at runtime, not compile time — hand it a double or a String and you get an IllegalFormatConversionException in production, so when the type is uncertain I default to %s. Inside templates I use %n rather than \n so the newline is platform-correct.
printf() is the same thing printed straight to the console, and since Java 15 there's "Hello %s".formatted(name) as a cleaner instance-method version. For anything beyond trivial gluing, I'd always pick a format template over concatenation.
String.format() in Java
Direct Answer
String.format(format, args...) returns text using Formatter syntax such as %s, %d, %.2f, and %n. The no-locale overload uses the default formatting locale, so use String.format(Locale.ROOT, ...) or a chosen locale when output must be stable. In logging frameworks, prefer their placeholder API instead of eagerly formatting a message.
Code Example
public class FormatDemo {
public static void main(String[] args) {
String name = "Alice";
int age = 28;
double score = 95.678;
// Basic usage — %s for string, %d for int, %f for double
String msg = String.format("Name: %s, Age: %d, Score: %f", name, age, score);
System.out.println(msg); // Name: Alice, Age: 28, Score: 95.678000
// Control decimal places with %.Nf
String scoreMsg = String.format("Score: %.2f", score);
System.out.println(scoreMsg); // Score: 95.68
// Padding and alignment
System.out.printf("%-15s %5d%n", "Alice", 95); // Alice 95
System.out.printf("%-15s %5d%n", "Bob", 72); // Bob 72
// printf() = String.format() + print — no assignment needed
System.out.printf("Hello, %s! You scored %d points.%n", name, (int) score);
// Hello, Alice! You scored 95 points.
// Using formatted() — instance method in Java 15+
String result = "User %s has %d tokens".formatted(name, 10);
System.out.println(result); // User Alice has 10 tokens
}
}
Common Mistakes & Pitfalls
- Passing a non-integer to
%d—String.format("%d", 3.14)throwsIllegalFormatConversionExceptionat runtime, not compile time, so it sails through your build and fails in production. Use%ffor decimals, or%swhen the type is uncertain. - Mismatching the argument count — too few arguments for the placeholders throws
MissingFormatArgumentException; the compiler can't catch it because the template is just a String. - Using
\ninstead of%nin a template —%nemits the platform line separator, while a hardcoded\nproduces the wrong line ending for Windows-style consumers and log parsers. - Expecting
%fto print clean decimals — bare%falways prints 6 digits (3.140000); use%.2fto control precision for prices and scores. - Reaching for
+on multi-value messages — concatenation is harder to read, easy to misorder, and painful to localize compared to a single template.
Check your understanding
Answer these without looking back at the article.
- What is the difference between String.format() and printf() in Java?
- What are Java text blocks and when were they introduced?
- What exception does String.format() throw if you use the wrong specifier type?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.