Java string intern and literal

Solution 1:

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

Solution 2:

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.