I have the following Test:
public class EqualityTest
{
String one = new String("Hello world");
String two = new String("Hello ") + new String("world");
@Test
public void testStringPool()
{
assertFalse(one == two); // FALSE!!!
assertTrue(one.equals(two));
assertTrue(one.intern().equals(two.intern()));
}
}
I would have expected that due to the String pool nature of Java, the VM would allocated one and two pointing to the same String in the pool. Why is my understanding wrong in this case?
Only string constants are interned automatically. So if your code had been:
… then
oneandtwowould have had the same value. Because you’ve usednew String(...), these expressions aren’t constant expressions, and so they aren’t interned. (The literals are still interned, of course… but not the strings created from the literals.)See section 15.28 of the JLS for details on what counts as a constant expression.