3

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?

Community
  • 1
  • 1
Jdoe
  • 75
  • 5

2 Answers2

3

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)

mprabhat
  • 20,107
  • 7
  • 46
  • 63
Subir Kumar Sao
  • 8,171
  • 3
  • 26
  • 47
-4

Because == means equal to so you are saying str1 and str2 equal each other.. AND that is true yes

SmilesNLulz
  • 31
  • 3
  • 8
  • This is not necessarily true. –  May 27 '12 at 17:55
  • 2
    @Hassan Leave out "necessarily" :) This is **never** true. There is **never** a comparison by string value done. – Marko Topolnik May 27 '12 at 17:56
  • Agreed, `==` returns `true` when twp *primitives* are equal, or when two objects point to the same location in memory (which is what primitives do anyways). Strings, when defined like they are by the OP, are internally routed to the same location in memory, so they are equal. – Jon Egeland May 27 '12 at 17:57
  • 1
    @Jon Just to make it perfectly clear, it's not the strings that are equal, but the reference vars themselves. – Marko Topolnik May 27 '12 at 17:57