3

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?

hata
  • 11,633
  • 6
  • 46
  • 69
cottonpower
  • 109
  • 3
  • Maybe beacause "hello" and "web" are literals and a and b are variables? – cottonpower Feb 13 '21 at 11:22
  • I would say that compiler optimizes that and reuses string references. So it is possibly compile time optimization. – Antoniossss Feb 13 '21 at 11:25
  • 2
    "But WHY Java treats these two operations differently?" The language spec says that `"a" + "b"` (as literals) is considered by the compiler identical to `"ab"`. `a + b` (as non-constant variables) is evaluated each time it is executed, constructing a new string. – Andy Turner Feb 13 '21 at 11:25
  • Your title is misleading, as the question does not use `+=`. – Andy Turner Feb 13 '21 at 11:26

0 Answers0