Is string interning done at compile time in Java? [duplicate]

风流意气都作罢 提交于 2019-11-30 06:43:23

The compiler puts the literal strings in the class file (and only unique ones, it consolidates all equivalent literals); the JVM loads those strings into the string pool when the class file is loaded.

If it is done at runtime then why can't the JVM figure out that they are the same String.

Because the string being returned by .substring has not been interned, and so is a different object than the equivalent "test" string in the string pool. If you interned it, you'd get true:

"test" == "!test".substring(1).intern() // true

Sections §4.4 of the JLS and §5.3 of the JVM spec look relevant.


Just to be clear: The correct way to compare strings in Java is to use the .equals method or similar, not ==. Using == with string instances is usually incorrect. (Unless you're playing with understanding when and how things are interned...)

I checked .class for

String a = "ABC";
String b = "ABC";

and found only one "ABC" in it. That is javac creates one constant of the same string at compile time.

But if 2 or more classes have the same "ABC" constant then JVM will place them at the same location in string pool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!