Possible Duplicate:
String equality vs equality of location
This my first question, be patient with me, please
I have the following code:
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2);
And the result is true
Why?
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.
When Java finds same literals during compile time it creates a single instance of it and refers that to all the references.
str1 and str2 both have same literals “hello” so jvm creates a single instance of it and assigns it to str1 and str2.
So when you do str1==str2 you get true. (Both are referencing to the same instance)