When to use intern() on String literals

前端 未结 4 1706
迷失自我
迷失自我 2020-11-30 00:22

I see a lot of legacy code like this:

class A {
    public static final String CONSTANT = \"value\".intern();
    ...
}

I don\'t see any re

4条回答
  •  天涯浪人
    2020-11-30 01:10

    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

提交回复
热议问题