-3

What's the difference in STRING.equals("myValue") vs STRING == "myValue"?

I first used STRING == "myValue" but my IDE recommends to switch to using .equals(). Is there a specific benefit to doing this?

Jayan
  • 18,003
  • 15
  • 89
  • 143
Ben
  • 60,438
  • 111
  • 314
  • 488
  • possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Rob Hruska Apr 11 '12 at 16:49
  • 1
    The truly preferred method is probably `"myValue".equals(STRING)`, since it avoids the possibility of a `NullPointerException`. – dlev Apr 11 '12 at 16:49
  • http://stackoverflow.com/questions/767372/java-string-equals-versus – Jayan Apr 11 '12 at 16:49
  • Check out [my answer to a similar question](http://stackoverflow.com/a/7311504/544963). – fireshadow52 Apr 11 '12 at 16:49
  • 2
    http://stackoverflow.com/questions/971954/difference-between-equals-and http://stackoverflow.com/questions/7311451/difference-between-equals-and-instanceof http://stackoverflow.com/questions/971954/difference-between-equals-and http://stackoverflow.com/questions/767372/java-string-equals-versus – Rob Hruska Apr 11 '12 at 16:53
  • This question has been asked twice today already. It a regular asked and answered. I wish google wouldn't keep going down so people could just search for the answers. When google the answer to this it only found 14 million results, I expected more ;) – Peter Lawrey Apr 11 '12 at 17:45

3 Answers3

8

Yes. Using == only compares the reference values; the equals() function actually checks whether or not the string contents are identical.

String x = new String("foo");
String y = new String("foo");
System.out.println(x == y); // prints false
System.out.println(x.equals(y)); // prints true
duffymo
  • 305,152
  • 44
  • 369
  • 561
1

I'm pretty sure == compares references, not values, while the .equals() does the value comparison.

Further reference.

Daniel Ribeiro
  • 10,156
  • 12
  • 47
  • 79
0

Yes, STRING == "myValue" won't work, because it will attempt to compare the references to the strings, and not the strings themselves.

.equals() way is the correct way and will give you the response you want.

Youssef G.
  • 617
  • 4
  • 10
  • 5
    Because the categorical statement that "`STRING == "myValue"` won't work" is *false*. It does work in many cases (due to interning.) – dlev Apr 11 '12 at 16:51
  • 1
    It doesn't work for what the question is imply. He won't get an error, but it will return false unless he is comparing the same string (and reference) to itself. I clarify that it "won't work" because its comparing reference values. – Youssef G. Apr 11 '12 at 16:53
  • @dlev - Can you explain the interning a little? It would seem that this is a boundary case, is it so common? – Caffeinated Apr 11 '12 at 16:53
  • 1
    @Adel This link explains it better than I could: http://javatechniques.com/blog/string-equality-and-interning/ – dlev Apr 11 '12 at 16:55