Codementor Events

Behind the scene of a concatenation of two strings using +(plus) operator.

Published Oct 31, 2019

Any Java Developer must have used one of the following while working with Strings.

  • String str1 = "hello " + "world";
  • String str2 = str + "of Java";
  • String str3 = str1 + str2;

The above 3 ways to concat a string using + operator work in different ways.
Let's get to them one by one.

1. String str1 = "hello " + "world";

You might be thinking that the above code takes two string literals and concatenate them to create a new String. But, this is not what happens. The java compiler (javac) is intelligent, it will detect that you are trying to add two string literals and automatically convert String str1 = "hello " + "world"; to String str1 = "hello world"; while creating the ".class" file.

2. String str2 = str + "of Java";

This again simply seems like two strings are being added, one is a string object and another is a string literal. Behind the scene code for it looks like this - String str2 = new StringBuilder(str).append("of Java").toString();. Yes, the + operator internally uses the append() method of StringBuilder to concat two strings.

3. String str3 = str1 + str2;

The same is the case with this one, it also uses the append() method of the StringBuilder. Behind the scene code this will look like this - String str3 = new StringBuilder(str1).append(str2).toString();

Discover and read more posts from Nikunj Gupta
get started