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?
Answer
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)
No comments:
Post a Comment