# Replace String Format by Formatted

# Description

Java 15 introduced a new instance method String::formatted​(Object... args) (opens new window) to format a string with the supplied arguments.

This rule replaces the static invocations of String.format​(String format, Object... args) (opens new window) by invocations of the new method described above. Thus, simplifying the code and improving the readability.

Requirements

  • Java 15

# Benefits

Removes code clutter. Improves readability.

# Tags

# Code Changes

# Invoking formatted

Pre

String output = String.format(
    "Name: %s, Phone: %s, Address: %s, Salary: $%.2f",
    name, phone, address, salary);

Post

String output = "Name: %s, Phone: %s, Address: %s, Salary: $%.2f"
                .formatted(name, phone, address, salary);

# Platform Independent Line Breaks

Pre

String output = String.format(
    "Name: %s %s%nAddress: %s%nPhone: %s",
    firstName, lastName, address, phone);

Post

String output = "Name: %s %s%nAddress: %s%nPhone: %s"
                .formatted(firstName, lastName, address, phone);

# Formatted Text Block

Pre

String output = String.format("""
		Name:    %s
		Phone:   %s
		Address: %s
		Salary:  $%.2f
		""", 
        name, phone, address, salary);

Post

String output = """
		Name:    %s
		Phone:   %s
		Address: %s
		Salary:  $%.2f
		""".formatted(name, phone, address, salary);

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID ReplaceStringFormatByFormatted
First seen in jSparrow version 4.3.0
Minimum Java version 15
Remediation cost 2 min