Are the below two pieces of code the same?
String foo = \"foo\";
String foo = new String(\"foo\").intern();
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
public String intern()
It follows that for any two strings s and t,
s.intern() == t.intern()
is true if and only ifs.equals(t)
istrue
.
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.
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
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.
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 thisString
object as determined by theequals(Object)
method, then the string from the pool is returned. Otherwise, thisString
object is added to the pool and a reference to thisString
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".