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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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.