SonarLint : Java - Strings should not be concatenated using '+' in a loop

SonarLint : Java - Strings should not be concatenated using '+' in a loop

Since string is an immutable object every time we add something to the string it is actually not directly added to the string, java internally convert the string to an intermediate object concate the string, and then again change it back to the string,

This can pose a serious performance issue when used with the long strings inside the loop , Therefore the use of string builder is preferred.

Noncompliant Code Example

String str = "";
for (int i = 0; i < arrayOfStrings.length ; ++i) {
  str = str + arrayOfStrings[i];
}

Compliant Solution

StringBuilder bld = new StringBuilder();
  for (int i = 0; i < arrayOfStrings.length; ++i) {
    bld.append(arrayOfStrings[i]);
  }
  String str = bld.toString();