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

Introduction to String::formatted

Understanding the formatted instance method added in Java 15 as an alternative to String.format.

Introduction to String::formatted

What you'll learn: You'll discover Java 15's formatted() instance method as a modern alternative to String.format().

The Core Idea

For years, Java developers have used the static method String.format() to create formatted strings with placeholders. Java 15 introduced formatted() as an instance method on String objects, providing a more fluent and readable way to accomplish the same task.

Instead of writing:

String.format("Hello, %s! You have %d messages.", name, count)

You can now write:

"Hello, %s! You have %d messages.".formatted(name, count)

Both produce identical results, but formatted() reads more naturally—the template string itself is the starting point, and you chain the formatting operation directly onto it.

Why It Matters

The formatted() method uses the same format specifiers (%s, %d, %f, etc.) and follows the same rules as String.format(). The difference is purely syntactic: it's a more modern, method-chaining style that fits well with functional programming patterns and fluent APIs.

Think of it like ordering at a coffee shop: String.format() is saying "Format, please make this drink with these ingredients," while formatted() is more like "This drink recipe—now make it with these ingredients." Same result, different approach.

When to Use It

Use formatted() when you prefer:

  • Method chaining style
  • Direct string template visibility
  • More compact multi-line formatting with text blocks (Java 13+)

Both format() and formatted() are equally valid—choose based on readability in your specific context.

Key Takeaway: String::formatted is Java 15's instance method alternative to String.format(), offering the same formatting power with a more fluent, chain-friendly syntax.