# Replace Concatenation with Infix-Operation

# 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.

# Tags

# 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;

# Bytecode JDK 1.8

Pre

public void original() {
    String value = "foo".concat("bar");
}
0 ldc #2 <foo>
2 ldc #3 <bar>
4 invokevirtual #4 <java/lang/String.concat>
7 astore_1
8 return

Post

public void transformed() {
    String value = "foo" + "bar";
}
0 ldc #5 <foobar>
2 astore_1
3 return

🛠️ 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 StringConcatToPlus
First seen in jSparrow version 1.0.0
Minimum Java version 1.1
Remediation cost 5 min