Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java string intern and literal

Are the below two pieces of code the same?

String foo = "foo";
String foo = new String("foo").intern();
like image 633
foo Avatar asked Apr 25 '11 09:04

foo


People also ask

Are string literals interned?

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

What is intern () in string?

The method intern() creates an exact copy of a String object in the heap memory and stores it in the String constant pool. Note that, if another String with the same contents exists in the String constant pool, then a new object won't be created and the new reference will point to the other String.

What is string and string literal in Java?

String literal in Java is a set of characters that is created by enclosing them inside a pair of double quotes. In contrast, String Object is a Java is a set of characters that is created using the new() operator.

Can we call intern method on literals?

substring(1). intern(),the method of intern() will put the ""! test". substring(1)" to the pool of literal strings,so in this case,they are same reference objects,so will return true.


1 Answers

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

like image 147
T.J. Crowder Avatar answered Oct 13 '22 20:10

T.J. Crowder