What's the difference between String.format() and str.formatted() in Java?

Learn what's the difference between string.format() and str.formatted() in java? with practical examples, diagrams, and best practices. Covers java, format, formatted development techniques with vi...

String.format() vs. str.formatted(): A Deep Dive into Java's Formatting Methods

Hero image for What's the difference between String.format() and str.formatted() in Java?

Explore the key differences, use cases, and performance considerations between Java's traditional String.format() and the newer str.formatted() method introduced in Java 15.

Java offers several ways to format strings, with String.format() being a long-standing staple for C-style formatting. However, with Java 15, a new instance method, str.formatted(), was introduced, providing a more object-oriented approach to the same task. While both methods achieve similar results, understanding their nuances, advantages, and when to use each is crucial for writing clean, efficient, and modern Java code. This article will break down these two methods, illustrating their functionalities with practical examples and discussing their implications.

String.format(): The Traditional Approach

String.format() is a static method that has been available since Java 1.5. It's heavily inspired by C's sprintf() function, allowing developers to create formatted strings using format specifiers. These specifiers dictate how arguments are converted and placed within the string. It's a versatile method, capable of handling various data types, alignment, precision, and locale-specific formatting.

public class TraditionalFormatting {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;
        double salary = 75000.50;

        // Basic formatting
        String message1 = String.format("Hello, %s! You are %d years old.", name, age);
        System.out.println(message1);

        // Formatting with precision and locale
        String message2 = String.format("Your salary is $%,.2f.", salary);
        System.out.println(message2);

        // Using argument index
        String message3 = String.format("The age is %2$d and the name is %1$s.", name, age);
        System.out.println(message3);
    }
}

Examples of using String.format() for various formatting needs.

str.formatted(): The Modern Instance Method

Introduced in Java 15 as part of JEP 355 (Text Blocks), str.formatted() is an instance method available on String objects. It provides a more fluent and object-oriented way to apply formatting. Essentially, str.formatted(Object... args) behaves identically to String.format(this, args), where this refers to the string instance on which the method is called. This means the string itself acts as the format string.

public class ModernFormatting {
    public static void main(String[] args) {
        String name = "Bob";
        int quantity = 5;
        double price = 19.99;

        // Using str.formatted() with a literal string
        String formatString1 = "Product: %s, Quantity: %d";
        String message1 = formatString1.formatted(name, quantity);
        System.out.println(message1);

        // Using str.formatted() with text blocks (Java 15+)
        String formatString2 = """
            Invoice Item:
            Name: %s
            Price: $%.2f
            """;
        String message2 = formatString2.formatted("Laptop", price);
        System.out.println(message2);
    }
}

Demonstrating str.formatted() with both regular strings and text blocks.

Key Differences and Use Cases

While both methods leverage the same underlying formatting engine and format specifiers, their primary distinction lies in their invocation style and typical use cases. String.format() is a static utility, often used when the format string is dynamically generated or passed as a parameter. str.formatted() is an instance method, making it ideal when the format string is a literal or an existing String object, especially in conjunction with text blocks.

flowchart TD
    A[Start]
    B{Format String Source?}
    C[Literal String / Text Block]
    D[Dynamic / External String]
    E[Call str.formatted()]
    F[Call String.format()]
    G[Formatted String Result]

    A --> B
    B -->|Literal/Text Block| C
    B -->|Dynamic/External| D
    C --> E
    D --> F
    E --> G
    F --> G

Decision flow for choosing between String.format() and str.formatted().

Performance Considerations

In terms of performance, there is no significant difference between String.format() and str.formatted(). Both methods delegate to the same internal formatting logic. The choice between them should primarily be based on code readability, maintainability, and the Java version you are targeting, rather than micro-optimizations related to performance.

In summary, String.format() is the classic, static utility method for string formatting, widely compatible across Java versions. str.formatted() is a modern, instance-based alternative introduced in Java 15, offering a more fluent syntax, especially beneficial with text blocks. For new projects targeting Java 15+, str.formatted() often leads to cleaner code when the format string is a literal. For older projects or when the format string is dynamic, String.format() remains the go-to choice.