When comparing two Strings in Java using the "==" operator, we know that we are comparing the object's addresses in memory. But we also know that in Java the String pool do exists, so values produced by String literals would be pooled. In a situation like the following, the booleans check1, check2 and check3 all seem the same to me:
String a = "a";
String b = "b";
String ab = "ab";
boolean check1 = (a + b == "ab");
boolean check2 = (a + b == ab);
System.out.println( check1 ); // false NO POOL
System.out.println( check2 ); // false NO POOL
String s1 = "hello" + " web";
String s2 = "hello web";
boolean check3 = ( s1 == s2 );
System.out.println( check3 ); // true POOL
However, check1 and check2 are false and check3 is true.
The reason I found is that, in the last check, Java first joins the two values and then check the string pools.Then it realizes that the value already exists in the pool and assigns the reference.
While check1 and check2 are false because a + b creates a new object in memory.
But WHY Java treats these two operations differently?