3

I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.

Is == bad? When should it and should it not be used? What's the difference?

Harikrishnan
  • 7,765
  • 13
  • 62
  • 113
  • using == for strings is, in general, terrible as it will compare objects rather than the contents of the objects – Bathsheba Oct 08 '13 at 11:13
  • You should read ths. http://www.thejavageek.com/2013/07/27/string-comparison-with-equals-and-assignment-operator/ – Prasad Kharkar Oct 08 '13 at 11:48
  • Did you just copy the text from [this question](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java?lq=1)? Why? – Jesper Oct 08 '13 at 12:17

3 Answers3

3

This is actually a funny question. Here it is slightly modified:

I've been using the * operator in my program to add all my numbers so far. However, I ran into a bug, changed one of them into + instead, and it fixed the bug.

Is * bad?

Answer: not at all bad! It just does not add numbers, though you may not notice when testing with 2*2.

Ingo
  • 36,037
  • 5
  • 53
  • 100
1

Yes, == is bad. If you compare object with ==, it compares if the objects are the same, and not if the objects are equal. For Strings you are lucky, that most of the time, equal Strings are actually referencing the same object, but that is not necessarily so.

See this post How do I compare strings in Java? for examples

Community
  • 1
  • 1
Thomas Oster
  • 421
  • 2
  • 10
1

== operator check for equality of the reference of left and right operand of the operator, however equals method check for the values of two objects.

When dealing with string it is advisable to use equals method when ever possible since sting has pool of object so if two string are compared using == operator it will return false even content is same due to difference of the reference. But equal method return true .

Amith Jayasekara
  • 421
  • 1
  • 4
  • 11