Java string intern and literal

后端 未结 5 521
太阳男子
太阳男子 2020-11-29 08:58

Are the below two pieces of code the same?

String foo = \"foo\";
String foo = new String(\"foo\").intern();
相关标签:
5条回答
  • 2020-11-29 09:02

    Explicitly constructing a new String object initialized to a literal produces a non-interned String. (Invoking intern() on this String would return a reference to the String from the intern table.)

    Taken from : http://javatechniques.com/public/java/docs/basics/string-equality.html

    0 讨论(0)
  • 2020-11-29 09:04

    public String intern()

    It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

    So I believe the answer is yes, although the second method will have to search through the pool.

    EDIT

    As sugegsted by T.J. Crowder

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    All literal strings and string-valued constant expressions are interned.

    0 讨论(0)
  • 2020-11-29 09:07

    The first one i.e.

        String foo = "foo";
    

    in this line, we are creating a String using String literals. That means the string is automatically saved in String Constant pool.

    In the 2nd one , i.e. -

        String foo = new String("foo").intern();
    

    Here we are creating a String using new String() & then manually saving it to the String constant pool. If we didn't have mentiones intern() , it would not have saved in the String constant pool.

    For more clarification, please refer to this link -

    http://javacodingtutorial.blogspot.com/2013/12/comparing-string-objects-intern-other.html

    0 讨论(0)
  • 2020-11-29 09:24

    Yes, they are same. Basically intern() returns a representation of a string that is unique across the VM. This means you can use == instead of .equals() to compare the strings, saving on performance.

    0 讨论(0)
  • 2020-11-29 09:25

    They have the same end result, but they are not the same (they'll produce different bytecode; the new String("foo").intern() version actually goes through those steps, producing a new string object, then interning it).

    Two relevant quotes from String#intern:

    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    All literal strings and string-valued constant expressions are interned.

    So the end result is the same: A variable referencing the interned string "foo".

    0 讨论(0)
提交回复
热议问题