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
internmethod is invoked, if the pool already contains a string equal to thisStringobject as determined by theequals(Object)method, then the string from the pool is returned. Otherwise, thisStringobject is added to the pool and a reference to thisStringobject 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".