What is the difference between these two following statements?
String s = \"text\";
String s = new String(\"text\");
One creates a String in the String Constant Pool
String s = "text";
the other one creates a string in the constant pool ("text"
) and another string in normal heap space (s
). Both strings will have the same value, that of "text".
String s = new String("text");
s
is then lost (eligible for GC) if later unused.
String literals on the other hand are reused. If you use "text"
in multiple places of your class it will in fact be one and only one String (i.e. multiple references to the same string in the pool).