I am trying to concatenate two strings, one string with some value and another with empty.
Example:
String string1="Great"
String string2="";
and concatenating these two string with concat function and + operator
Example:
String cat=string1.concat(string2)
String operator=string1+string2
As per my understanding, while using empty string in concat function as the string2 is empty no new reference will be created. But while using + operator a new reference will be created in the string pool constant. But in the below code while using the + operator new reference is not created.
public class Main {
public static void main(String[] args) {
String string1="Great",string2="";
String cat=string1.concat(string2);
if(string1==cat)
{
System.out.println("Same");
}
else
{
System.out.println("Not same");
}
String operator=string1+string2;
if(operator==string1)
System.out.println("Same");
else
System.out.println("Not same");
}
}
Output:
string 1 :69066349
cat :69066349
Same
string1 :69066349
operator :69066349
Not same
From the above code, as it's using + operator, the reference for the variable : operator should refer to the new memory, but it's pointing to the string1 reference. Please explain the above code.