When you use ==
operator to check the equality of Strings, it checks if the location of the Strings in the memory is the same.
In cases 2 and 4, the Strings "hello" and "hello123" will already be in the String Constant Pool (due to lines 1 and 3) and will be recognized as equivalent to those Strings, and will use the same place in memory for each. In simple terms, it will create a String object and plug it into both instances of "hello" and "hello123".
When you do:
String s4=s+"123";
At run time, it creates a new memory location for s4
, since, the JLS says that:
Strings computed by concatenation at run-time are newly created and therefore distinct.
So, the memory locations are different, and hence it gives false
as the output.