Difference between string object and string literal

user395617 picture user395617 · Jul 21, 2010 · Viewed 277.3k times · Source

What is the difference between

String str = new String("abc");

and

String str = "abc";

Answer

Mark Byers picture Mark Byers · Jul 21, 2010

When you use a string literal the string can be interned, but when you use new String("...") you get a new string object.

In this example both string literals refer the same object:

String a = "abc"; 
String b = "abc";
System.out.println(a == b);  // true

Here, 2 different objects are created and they have different references:

String c = new String("abc");
String d = new String("abc");
System.out.println(c == d);  // false

In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.