0

Why this statement is bad practice :

String colour= new String("Blue"); 

and what's difference with this statement

String colour="Blue"; 
jww
  • 97,681
  • 90
  • 411
  • 885
Eman Habib
  • 11
  • 2
  • Possibly related: [String object instantiation](http://stackoverflow.com/q/16742819). – jww Jul 11 '15 at 01:24
  • 3
    *"Why this statement is bad practice"* - One reason is that it is pointless. Just like comments in your code about your favourite colour is. – Stephen C Jul 11 '15 at 01:26
  • 1
    This is because of the immutability of String. For more information have a look at this tutorial http://www.javahelps.com/2015/03/immutability-of-string.html – Gobinath Jul 11 '15 at 03:52

2 Answers2

0

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.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

You're creating an unnecessary String object.

String colour= new String("Blue");

"Blue" is already a String type.

ALD
  • 48
  • 5