I was testing around Strings, and I came up with below code:
public static void main(String[] args){
StringBuilder sb1 = new StringBuilder("Cuba");
String str1 = sb1.toString();
// n1
System.out.println(str1 == str2);
}
On n1
if I place:
String str2 = sb1.toString();
I get false
. However if I place:
String str2 = str1;
I get true
.
I am not sure why this is happening: both codes are referring to the same instance, therefore, both output must be true
.
Any idea why both output differ? I know how to compare Strings, I am just curious about the reason why the result differ.