Search code examples
junitassertions

assertSame() weirdness?


Can someone explain me this?

    String str1 = "123";
    String str2 = "123";
    assertSame(str1,str2); // works

    assertSame("1", new String("1")); // fails

Why does the first assert work, but not the second? Doesn't make sense to me. I didn't make a String comparison - which should have been done by assertEquals() - but a mere Object comparison. In my view the first assertSame(str1,str2) should fail too, because it does not reference to the same instance.


Solution

  • The compiler distills both references to the literal "123" into the same entry in the constant pool in the bytecode, so they are treated as identical.

    However, "123" and new String("123") are distinct objects, though they contain the same characters, so assertSame() fails. assertEquals() would succeed in both cases.