What is the difference Between Assignment and Creating Instance of String?
String s = "Test";
Will first look for the String "Test" in the string constant pool. If found s will be made to refer to the found object. If not found, a new String object is created, added to the pool and s is made to refer to the newly created object.
String s = new String("Test");
Will first create a new string object and make s refer to it. Additionally an entry for string "Test" is made in the string constant pool, if its not already there.
So assuming string "Test" is not in the pool, the first declaration will create one object while the second will create two objects.
The differnce in term of memory is that the expressions of the form :
String s = "test"
uses the "interned" string so as to share unique instances.
The invocation of form: String s = "test"
is efficient compared to String s = new String("test")
The first call makes use of the existing constant expression (if there is one), the second call creates a new instance without making use of any existing instance.
Below code chunk demonstrates this:
String test = new String("test");
String internTest = "test";
String nonInternTest = new String("test");
System.out.println(test == internTest); // prints false
System.out.println(test != nonInternTest); // prints true
System.out.println(test.equals(nonInternTest)); // prints true
Also note that the JLS specifies the behavior to be thus:
Each string literal is a reference to an instance of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions are "interned" so as to share unique instances, using the method String.intern.