PPT Slide
Why are Strings treated differently?
Strings are sometimes a special case of equivalency in Java. When the compiler encounters the lines:
String strHello1 = “Hello”;
String strHello2 = “Hello”;
the compiler is smart enough to know that the two Strings are identical. So, it decides it will save a few bytes of memory and point to the same location in memory. The same result would occur even if you wrote:
String strHello2 = “Hell” + “o”;
This means that for the above lines of code,
equals() and ‘==‘ both work:
(strHello1.equals(strHello2)); // true
(strHello1 == strHello2); // also true,