Behind the scene of a concatenation of two strings using +(plus) operator.
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.
String str1 = "hello " + "world";
1. 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.
String str2 = str + "of Java";
2. 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.
String str3 = str1 + str2;
3. 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();