What You'll Learn
You'll learn how to use the formatted() method with common format specifiers (%s, %d, %f) to insert values into strings cleanly and readably.
Understanding Format Specifiers
The formatted() method (introduced in Java 15) lets you create strings with placeholders that get replaced by actual values. Think of it like a template with blanks you fill in: "Hello, ____! You scored ____ points."
Instead of blanks, you use format specifiers — special codes that begin with % and indicate what type of value goes there.
The Three Most Common Specifiers
%s — String Substitution
Replace %s with any string value:
String name = "Alice";
String message = "Hello, %s!".formatted(name);
// Result: "Hello, Alice!"
%d — Decimal Integer Substitution
Replace %d with an integer value:
int score = 95;
String result = "You scored %d points.".formatted(score);
// Result: "You scored 95 points."
%f — Floating-Point Number Substitution
Replace %f with a decimal number:
double price = 19.99;
String receipt = "Total: $%f".formatted(price);
// Result: "Total: $19.990000"
Multiple Substitutions
You can use multiple specifiers in one string. The values are substituted in order:
String report = "Player %s scored %d points with %.2f accuracy."
.formatted("Bob", 87, 0.923);
// Result: "Player Bob scored 87 points with 0.92 accuracy."
Notice %.2f — the .2 limits the output to 2 decimal places.
Why This Matters
Format specifiers make string building cleaner than concatenation or multiple replace() calls, especially when mixing different data types.
Key Takeaway: Use %s for strings, %d for integers, and %f for decimals with the formatted() method to create readable, template-based strings with type-safe substitution.