I have the following simple piece of java code where I am trying to understand how string concatenation in java works using '+' operator.
public class Problem {
public static void main(String... args){
String str1 = "abc";
String str2 = "ab";
String str3 = "c";
String str4 = "ab" + "c";//This will use of StringBuilder class for concatenation and return new String object
String str5 = str2 + str3;//This will use of StringBuilder class for concatenation and return new String object
System.out.println(str1 == str4); // This returns true
System.out.println(str1 == str5); // This returns false
}
}
str4
is the resultant of 2 string literals (ab
and c
) and str5
is of references to the 2 string literals (str2
and str3
). In both the cases, java will be calling StringBuilder class to perform the concatenation.
And I believe it should result in creating 2 different StringBuilder objects in java heap space.
If my understanding is correct, why str1 == str4
returns true ? Can some one please help in getting this clear to me ?
Regards, Maneesh Sharma