Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why two strings with the same name have the same object instance? [duplicate]

Tags:

java

instance

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?

like image 892
Jdoe Avatar asked Jul 25 '26 02:07

Jdoe


1 Answers

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)

like image 173
Subir Kumar Sao Avatar answered Jul 27 '26 18:07

Subir Kumar Sao