Replace Concatenation with Infix-Operation

Properties

Property Value
First seen in jSparrow version 1.0.0
Minimum Java version 1.1
Remediation cost 5 min

Description

This rule replaces the concat() method on Strings with the + operator.

For example, s = s.concat("bar") becomes s = s + "bar". This improves readability and performance for chained concatenations.

Benefits

Applying this rule has slight performance benefits and arguably improves readability. The Java compiler will convert the + operation to use a StringBuilder. The more concatenations occur, the bigger the performance gain is.

Requirement & Tags

Requirements

None

Code Changes

Base case

Pre

String s = "foo";
s = s.concat("bar");

Post

String s = "foo";
s = s + "bar";

Chained concatenation expression

Pre

input.concat("abc").concat("cde").concat("fgh".concat("hij"));

Post

input + "abc" + "cde" + "fgh" + "hij";

Nested concatenation expressions

Pre

input.concat(param.concat(param));

Post

input + param + param;