what is the Difference between string object and string literal?

What is the difference between

String str = new String(“Welcome”);


String str = “Welcome”;

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 = "Welcome";

String b = "Welcome";

System.out.println(a == b);  // True

Here two different objects are created and they have different references:


String c = new String("Welcome");

String d = new String("Welcome");

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.