Posted In: Java Core, String

When to use StringBuilder vs String concatenation

Most of the discussions say that for few fields String concatenation is fine. If code is looping then do use StringBuilder.
Use StringBuilder for following kind of code

public String concanate() {
	String s = "";
	for (int i = 0; i < 1000; i++) {
		s += i;
	return s;

There is slight different issue with this may be approach. Applications which go through various static code analysis tools should always use StringBuilder append than String concatenation. These tools are configured these checks and unnecessarily you will receive code warnings.

PMD rule which displays warning for String concatenation

Since: PMD 3.1

The use of the ‘+=’ operator for appending strings causes the JVM to create and use an internal StringBuffer. If a non-trivial number of these concatenations are being used then the explicit use of a StringBuilder or threadsafe StringBuffer is recommended to avoid this.

This rule is defined by the following Java class:

by , on August 24th, 2017

  • Categories