You should use some form of the String#equals(Object)
method. However, there is some subtlety in how you should do it:
If you have a string literal then you should use it like this:
"Hello".equals(someString);
This is because the string literal "Hello"
can never be null, so you will never run into a NullPointerException
.
If you have a string and another object then you should use:
myString.equals(myObject);
You can make sure you are actually getting string equality by doing this. For all you know, myObject
could be of a class that always returns true
in its equals
method!
Start with the object less likely to be null because this:
String foo = null;
String bar = "hello";
foo.equals(bar);
will throw a NullPointerException
, but this:
String foo = null;
String bar = "hello";
bar.equals(foo);
will not. String#equals(Object)
will correctly handle the case when its parameter is null, so you only need to worry about the object you are dereferencing--the first object.