简体   繁体   中英

Java string intern and literal

Are the below two pieces of code the same?

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

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".

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 TJ 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.

The first one ie

    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 , ie -

    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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM