In Java, what is the difference between String s = “abc” and String s = new String (“abc”)?
Answered
In Java, what is the difference between String s = “abc” and String s = new String (“abc”)?
Best answer
String s=”abc” is a String literal. Here String s refers to an interned String object. This means, that the character sequence “abc” will be stored at a central place (common pool) and whenever the same literal “abc” is used again, the JVM will not create a new String object but use the reference of the ‘cached’ String.
String s= new String (“abc”) is guaranteed to be a new String object. String objects created using ‘new’ operator are stored in the heap.
So if,
String s1="abc"; String s2="abc"; String s3 = new String("abc"); String s4 = new String("abc");
(s1 == s2) is true
s1.equals(s2) is true
(s3 == s4) is false
s3.equals(s4) is true