Skip to main content

Command Palette

Search for a command to run...

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

Published
1 min read
SonarLint : Java - Strings should not be concatenated using '+' in a loop
S

I love learning about technology and sharing that with others

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();
81 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)