I see a lot of legacy code like this:
class A { public static final String CONSTANT = "value".intern(); ... }
I don't see any reason for the intern(), as in the Javadoc one can read: "All literal strings and string-valued constant expressions are interned." Is there some intent of this, maybe in past revisions of the language?
The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.
The intern() method helps in comparing two String objects with == operator by looking into the pre-existing pool of string literals, no doubt it is faster than equals() method. The pool of strings in Java is maintained for saving space and for faster comparisons.
The Java String class intern() method returns the interned string. It returns the canonical representation of string. It can be used to return string from memory if it is created by a new keyword. It creates an exact copy of the heap string object in the String Constant Pool.
intern() in Java. All compile-time constant strings in Java are automatically interned using this method.
This is a technique to ensure that CONSTANT
is not actually a constant.
When the Java compiler sees a reference to a final static primitive or String, it inserts the actual value of that constant into the class that uses it. If you then change the constant value in the defining class but don't recompile the using class, it will continue to use the old value.
By calling intern() on the "constant" string, it is no longer considered a static constant by the compiler, so the using class will actually access the defining class' member on each use.
JLS citations:
definition of a compile-time constant: http://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#5313
implication of changes to a compile-time constant (about halfway down the page): http://docs.oracle.com/javase/specs/jls/se6/html/binaryComp.html#45139
The use of intern()
with the constant string literal is a waste of time as the literal will already be interned as specified by section 3.10.5. String Literals of The Java® Language Specification.
Quoting from Java SE 8 Edition:
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
I guess the coder didn't appreciate this fact.
Edit:
As kdgregory has pointed out there is an impact on how this constant may be inlined.
1- https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-3.10.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With