00 Votes

Java: How to compare Strings correctly

Question by Guest | 2016-07-11 at 11:25

I am not doing Java programming for a long time and again and again I am encountering problems with a simple string comparison.

From other programming languages, I am used to just compare strings with the operator "==". The result is true if the strings are equal, false instead.

However, in Java, I have frequently observed a strange behavior with this comparison. Sometimes, it is working, sometimes not. Do I have to consider something else with this? How can I compare Java strings correctly if this is not the correct way?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, you have to take something into account. That is the difference between comparing with == and comparing with .equals().

  • With == you are checking for the same reference, that is for example that two variables are pointing to the same object.
  • With .equals() you are checking for the same value, that is for example whether two strings have the same content, independent from whether the object is also the same or not.

So, if you are in your case only interested in comparing the content or value of a string, you have to use .equals() instead of "==".

Your observation that "==" is sometimes working and sometimes not is probably because you have from time to time indeed compared strings having the same reference. However, if the string value is the same, but not the reference, the result of the == comparison was accordingly false.

Here is a small example demonstrating the difference:

String a = new String("abc");
String b = new String("abc");
String c = a;

if (a == b) {
  // FALSE because reference is not equal
}

if (a == c) {
  // TRUE because reference is the same
}

if (a.equals(b)) {
  // TRUE because content is the same
}

By the way, with .equals() you are always also checking for an identical uppercase and lowercase writing. If you do not want to consider the writing, you can use .equalsIgnoreCase() instead.
2016-07-11 at 17:29

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.