When comparing two strings, I was taught that we shouldn\'t use the logical operator (==). We should use String.equals(String) for the comparison. However, I see that the fo
The magic is called interning.
Java interns String literals and so there is a high probability that it evaluates to true:
String a = "hello"; // "hello" is assigned *and* interned
String b = "hello"; // b gets a reference to the interned literal
if (a == b)
System.out.println("internd.");
String c = "hello" + Math.abs(1.0); // result String is not interned
String d = "hello" + Math.abs(1.0); // result String is not interned
System.out.println(c==d); // prints "false"
c = c.intern();
System.out.println(c==d); // prints "false"
d = d.intern();
System.out.println(c==d); // prints "true"