I tested the lines and I came up with the code below:
public static void main(String[] args){
StringBuilder sb1 = new StringBuilder("Cuba");
String str1 = sb1.toString();
System.out.println(str1 == str2);
}
In n1if I put:
String str2 = sb1.toString();
I get it false. However, if I put:
String str2 = str1;
I get it true.
I'm not sure why this happens: both codes refer to the same instance, so both outputs should be true.
Any idea why both outputs are different? I know how to compare strings, I'm just wondering why the result is different.
source
share