Tuesday, March 14, 2017

Difference between string object and string literal

Question:

What is the difference between

String str = new String("abc");

and

String str = "abc";


Answer:

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.

No comments:

Post a Comment