String concatenation and StringBuilders


String concatenation can be performed using the + operator. For example:

String x1 = "hello";
String x2 = "world";
String x3 = "!";
String result = x1 + x2 + x3; // helloworld!

Normally a compiler implementation will perform the above concatenation using methods involving a StringBuilder under the hood. When compiled, the code would look similar to the below:

StringBuilder builder = new StringBuilder("x");
String phrase = builder.append("y").append("z").toString();

StringBuilder has several overloaded methods for appending different types, for example, to append an int instead of a String. For example, an implementation can convert:

String str1 = "X";
String str2 = "Y";
String result = str1 + str2 + 5; // XY5

to the following:

StringBuilder builder = new StringBuilder("X");
String result = builder.append("Y").append(7).toString(); // XY7

The above examples illustrate a simple concatenation operation that is effectively done in a single place in the code. The concatenation involves a single instance of the StringBuilder. In some cases, a concatenation is carried out in a cumulative way such as in a loop:

String finalString = "";
for(int index = 0; index < elementsArray.length; index++)
{
    finalString += extractElement(elementsArray[index]);
}
return finalString;

In such cases, the compiler optimization is usually not applied, and each iteration will create a new StringBuilder object. This can be optimized by explicitly transforming the code to use a single StringBuilder:

StringBuilder finalResult = new StringBuilder();
for(int index = 0; index < elements.length; index++)
{
    finalResult.append(extractElement(elements[index]));
}
return finalResult.toString();

A StringBuilder will be initialized with an empty space of only 16 characters. If you know in advance that you will be building larger strings, it can be beneficial to initialize it with sufficient size in advance, so that the internal buffer does not need to be resized:

StringBuilder buffer = new StringBuilder(25); // Initial capacity set to 25 characters
buffer.append("Hello ");
buffer.append("World!"); // Expands the buffer to accommodate the extra characters
String finalResult = buffer.toString(); // Contains the concatenated string

If you are producing many strings, it is advisable to reuse StringBuilders:

StringBuilder stringBuilder = new StringBuilder(50);
for (int i = 0; i < 50; i++)
{
    stringBuilder.setLength(0); // Clear buffer
    stringBuilder.append("Iteration ").append(i).append('\n');
    someOtherFile.write(stringBuilder.toString());
}

If (and only if) multiple threads are writing to the same buffer, use StringBuffer, which is a synchronized version of StringBuilder. But because usually only a single thread writes to a buffer, it is usually faster to use StringBuilder without synchronization.

Using concat() method:

String str1 = "Good ";
String str2 = "morning!";
String str3 = str1.concat(str2); // "Good morning!"

This returns a new string that is str1 with str2 added to it at the end. You can also use the concat() method with string literals, as in:

"My Name is ".concat("Tiya");

Basic Programs