What is the difference between these two statements?
String str = "stackoverflow";
&
String str = new String("stackoverflow");
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.
It differs in how the string is taken from pool.
1.
When you say,
It will first check if
"stackoverflow"already exists in String pool. If it does, then it will use the same from pool.This is the reason why when,
The result of above will be true, because same String object from pool is used.
2.
When you do,
Always, a new String object is created, irrespective of a same one already exists in pool or not.
So,
Here, str2 and str3 will again create a new String object.
so, str2, str3 and str1 all refer to different objetcts and
str2!=str3!=str1