Why this statement is bad practice :
String colour= new String("Blue");
and what's difference with this statement
String colour="Blue";
Why this statement is bad practice :
String colour= new String("Blue");
and what's difference with this statement
String colour="Blue";
The first is discouraged because it reads a String
from the String
intern pool and then instantiates a new object instance. The Wikipedia article on String interning says (in part)
In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.
The second example assigns a reference to the String
from the intern pool.
You're creating an unnecessary String object.
String colour= new String("Blue");
"Blue" is already a String type.