# 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);
You Want To Have Those Changes Done Automatically?
The automatic application of this rule is supported in the following jSparrow version:
# Properties
Property | Value |
---|---|
Rule ID | ReplaceStringFormatByFormatted |
First seen in jSparrow version | 4.3.0 |
Minimum Java version | 15 |
Remediation cost | 2 min |