When String.format() is used with simple %s placeholders, the result can often be achieved more clearly with String.valueOf() or string concatenation. These simpler alternatives are easier to read, maintain, and slightly more efficient.

Why is this an issue?

String formatting utilities like String.format() are powerful mechanisms for creating formatted strings with complex patterns. However, they come with overhead: parsing format specifications, identifying placeholders, performing type conversions, and assembling the result.

When the formatting pattern is simple enough that it can be replaced with a more direct alternative — such as String.valueOf() for a single %s placeholder, or plain string concatenation for a few %s placeholders joined by literal text — using a formatting utility adds unnecessary complexity.

This has several drawbacks:

Using simpler alternatives makes the intent of the code immediately clear without requiring readers to mentally parse a format string.

What is the potential impact?

This issue primarily affects code maintainability. The code becomes harder to read and understand because string formatting functions signal to readers that some formatting is happening, when in fact none is needed.

There is also a minor performance impact, especially if the redundant call occurs in a loop or frequently executed code path. While the overhead is typically small, it’s completely avoidable.

How to fix it

When the format string contains a single %s placeholder and nothing else, replace String.format() with String.valueOf().

When the format string contains %s placeholders joined by literal text, replace String.format() with string concatenation.

Code examples

Noncompliant code example

String name = String.format("%s", user.getName()); // Noncompliant - use String.valueOf()
String path = String.format("%s/%s", directory, filename); // Noncompliant - use concatenation
String label = String.format("%s: %s", key, value); // Noncompliant - use concatenation

Compliant solution

String name = String.valueOf(user.getName());
String path = directory + "/" + filename;
String label = key + ": " + value;

These usages are compliant because they use format specifiers that have no simple concatenation equivalent:

String price = String.format("%.2f", amount);                  // Compliant - decimal formatting
String hex = String.format("0x%08X", value);                   // Compliant - hex with padding
String table = String.format("%-20s %5d", name, count);        // Compliant - width/alignment
String date = String.format("%tF %tT", timestamp, timestamp);  // Compliant - date/time formatting

Resources

Documentation