[LD] Java - Fun Facts - String Equality | Let's Developer With

preview_player
Показать описание
I thought I know how Strings and == behave. I was wrong...

«Other Series»
Рекомендации по теме
Комментарии
Автор

Hi Sven,

The reason for this behaviour is that in all the cases where the assertion works javac is able to statically compute the contents of the string. Hence, the same reference from the string pool can be used. If you look into the byte code, you'll see that there is never a call to NEW java/lang/String. In fact, even a statement like "ab" + "c" is resolved to LDC "abc". If you explicitly invoke the constructor of String, the comparison will fail: assertTrue("abc" == new String("abc")); String interning works on a per-JVM basis, not per class basis (otherwise it would be quite useless).

HTH
Moritz

inventitech