views:

232

answers:

5

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?

+4  A: 
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.

codaddict
As I understand it, the lookup/object creation in the constant pool happens for all literals occuring in a class's code when that class is loaded, not when that particular line of code is executed.
Michael Borgwardt
+3  A: 
sateesh
A: 

First one will search the String literal "Test" in the String pool, if it is present then s will refer that and will not create new one. and creates new object only when "Test" literal is not there.

but in the second case it will create an another object without bothering much about whether it is present or not.

GK
+1  A: 

String s = "Test"; // creates one String object and one reference variable In this simple case, "Test" will go in the pool and s will refer to it.

String s = new String("Test"); // creates two objects and one reference variable In this case, because we used the new keyword, Java will create a new String object in normal (non-pool) memory, and s will refer to it. In addition, the literal "Test" will be placed in the pool.

but what they have in common is that they all create a new String object, with a value of "Test", and assign it to a reference variable s.

sap
A: 

+The differnce between creating a new String objectand creating reference is nothing but we are telling to jvm to create a new object. and create the refence means we are creating the object our self only.

anand