Friday 29 April 2016

java - Why two strings with the same name have the same object instance?











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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...