What is the difference Between Assignment and Creating Instance of String?

java, memory, string

Solution

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.

Problem

In an interview question, Interviewer asked me What is the common and difference between the following statements: ``` String s = "Test"; String s = new String("Test"); ``` Is there any difference in memory allocation?

Original source

Related problems