Last Updated:

String Concatenation in Java - Methods and Examples

Surely you have already heard that when working with strings, namely concatenation, it is not advisable to use the "+" operator. Use StringBuffer or StringBuilder for this purpose. It should be noted that this question is one of the most frequently asked during an interview for the position of Java Junior Developer on Java Core.

But still, let's look at all the most used ways to concatenate strings and analyze what happens "along the hood" of these methods.

Concatenate strings using the "+" operator

Concatenate Strings with StringBuffer

Now let's look at the same program, but using StringBuffer:

The string concatenation code using StringBuilder will be similar to the one above.

Analyze the performance of the "+" operator and StringBuffer

So, let's see what happens "under the hood" of our program when we use the "+" operator and StringBuffer or StringBuilder.

When we combine strings using the "+" operator, the following happens:

  1. A new StringBuilder object is created.
  2. The string "Prologistic" is copied to the newly created StringBuilder object.
  3. A method is called to append the string "" to the StringBuilder object.append()
  4. A method is called to get a String object from a StringBuilder object.toString()
  5. A reference to the newly created String object is assigned to simpleString, and the old string "Prologistic" becomes available to the garbage collector.

And what happens if we use StringBuffer or StringBuilder:

  1. A new StringBuffer object is created with the value "Prologistic".
  2. A method is called to append the string "" to the object.append()
  3. A method is called to get a String object from a StringBuffer object.toString()

Judging by the number of steps required to concatenate strings, a method using a StringBuffer or StringBuilder is less time-consuming, uses fewer resources, and produces less garbage for the garbage collector.