I am comparing two strings, and apparently they aren't equal but they are. I was wondering what are some issues that could cause this, maybe datatype, hidden stuff that I can't see, or what. Any input could be helpful. Thanks.
-
You're **not** doing value comparison; the `==` operator when applied to objects does *reference* comparison - it will only return true if they're the exact same object. – Anthony Grist Jan 17 '13 at 16:10
4 Answers
String/Object comparison should use equals()
, not ==
(excepts the case of String literal comparison)
Example:
if(string.equals(string2)){
}
==
checks for reference equality, equals()
checks for content equality. Read this discussion.
-
1Just to add to this: == checks whether the references to the objects are equal, .equals() checks for character sequence equality – Justin Jasmann Jan 17 '13 at 16:11
-
-
@user1582340: Don't know about C++, but it is true in Java, not true in .NET – kosa Jan 17 '13 at 16:16
-
Personally, I'd avoid using `==` even when comparing String literals in Java, in case one of them _stops_ being a literal. – Clockwork-Muse Jan 17 '13 at 16:34
field.trim().equalsIgnoreCase("formDateCreated")
Try this. String trim() Method returns a copy of the string, with leading and trailing whitespace omitted.

- 12,735
- 2
- 27
- 39
-
-
Yes,I know but may be user1582340 getting problem because of this. – Achintya Jha Jan 17 '13 at 16:27
-
No trim is note the issue. But you don't need to trim() this "formDateCreated" – someone Jan 17 '13 at 16:28
use .equals()
method to check for String equality like field1.equals("formDateCreated")
.
==
operator just checks if two reference variables refer to the same string instance. equals()
method checks if two strings are meaningfully equal.

- 6,577
- 7
- 37
- 60

- 45,977
- 8
- 87
- 106
equalsIgnoreCase(String anotherString)
for when you are not consider about case. This check weather your string content is equal not the reference which is ==
I would suggest you to check like bellow
"formDateCreated".equalsIgnoreCase(field)
So that it helps you to overcome possible NullPointerException

- 6,577
- 7
- 37
- 60