# 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);
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.
# Properties
Property | Value |
---|---|
Rule ID | ReplaceStringFormatByFormatted |
First seen in jSparrow version | 4.3.0 |
Minimum Java version | 15 |
Remediation cost | 2 min |