# Replace Concatenation with Infix-Operation

# Properties

Property Value
Rule ID StringConcatToPlus
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.

# 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

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version:

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊