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?
Related Topics
Java: Smaller/Larger Comparison of Strings - The operator > is undefined for the argument type(s) java.lang.String
Question | 1 Answer
Java: Case Insensitive Equals - String Comparison
Info | 0 Comments
Java/Android: String comparison s1==s2 does not work
Question | 1 Answer
Android Programming: Send data via HTTP POST request
Tutorial | 0 Comments
Java: Split at point str.split(".") does not work
Question | 1 Answer
Windows API: GetProfileString and GetPrivateProfileString clears quotes
Question | 1 Answer
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.
Yes, you have to take something into account. That is the difference between comparing with == and comparing with .equals().
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:
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