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

formatted vs String.format

Comparing the instance method approach with the static method and when to prefer each.

formatted vs String.format

You'll learn: How the formatted() instance method differs from String.format() static method and when to choose one over the other.

The Core Difference

Both methods perform the same formatting operation, but they differ in how you invoke them:

  • String.format(format, args) is a static method that takes the format string as the first parameter
  • formatString.formatted(args) is an instance method (Java 15+) called on the format string itself

Think of it like asking a librarian to find a book versus using a self-service catalog: both get you the book, but the approach feels different.

Comparing the Approaches

// Static method approach
String result1 = String.format("Hello, %s! You have %d messages.", "Alice", 5);

// Instance method approach
String result2 = "Hello, %s! You have %d messages.".formatted("Alice", 5);

Both produce identical output: "Hello, Alice! You have 5 messages."

When to Prefer Each

Use formatted() when:

  • You're working with string literals or constants directly
  • You want more fluent, readable method chains
  • You prefer the "object-oriented" feel of calling a method on the format string

Use String.format() when:

  • You need Java 14 or earlier compatibility
  • The format string is built dynamically or comes from a variable
  • Your team is more familiar with the classic approach
// Instance method feels natural with literals
String msg = "Score: %d%%".formatted(95);

// Static method works better with dynamic formats
String template = getFormatFromConfig();
String result = String.format(template, value);

Key Takeaway: formatted() and String.format() produce identical results—choose based on readability, version compatibility, and whether your format string is a literal or variable.