Sting *LITERALS* are always allocated once, only, out of a static pool.
So what you have *really* done here is equivalent this:
a = System.getStringFromLiteralPool("hi");
b = System.getStringFromLiteralPool("hi");
so a and b are *really* referring to *EXACTLY* the same object. And so the == operator really is testing object equivalence!
FWIW, you actually *can* force Java to see a pair of dynamically created strings as the same object, if they contain the same characters. You have to call the intern()
method and then use the returned reference.
Here, look at this:
Essentially, *all* string literals are automatically returned via hidden calls to intern().