Inspired by the comments on this question, I’m pretty sure that Java Strings are interned at runtime rather than compile time – surely just the fact that classes can be compiled at different times, but would still point to the same reference at runtime.
I can’t seem to find any evidence to back this up. Can anyone justify this?
The optimization happens (or at least can happen) in both places:
Stringobject created in the JVM, but it’s an obvious optimization to make. This isn’t actually interning as such – just constant optimization.(I have a vague recollection that one of the bits of work for Java 7 around “small jar files” included a single string pool for the whole jar file… but I could be very wrong.)
EDIT: Section 5.1 of the JVM spec, “The Runtime Constant Pool” goes into details of this: