I know it's not possible to call the equals method on a null object like that:
//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2))
{
System.out.println("NOT WORKING :'(");
}
But in my case I want to compare two objects from two database and these two objects can have attributes null...
So what is the method to compare two attributes, knowing that we are not sure that the value is null or filled.
This method is good or not ?
//WORKING
String s1 = "test";
String s2 = "test";
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}
//WORKING
String s1 = null;
String s2 = null;
if(s1 == s2 || s1.equals(s2))
{
System.out.println("WORKING :)");
}
I'm not sure because in this case it's not working ... :
//NOT WORKING
String s1 = null;
String s2 = null;
if(s1.equals(s2)|| s1 == s2 )
{
System.out.println("NOT WORKING :'''(");
}
Invoking a dot operator (call method or object properties) on null object will always throw RuntimeException (Exception are the static members as they don't belong to the object but to the class).
The chunk of code works only because || is a shortcut operator:
it does not evaluate the right side if the left side is true.
Same for the &&: it does not evaluate the right side if the left side is false.
Another option to use:
The reason you're getting a NullPointerException when doing
s1.equals(s2)
withs1
being null is not because of s2 being null, but because you are trying to invoke the equals method on s1, which is null.Try to amend it like this:
Also note that if s1 is not null and s2 is, you'll get a
false
back from equals, but no NullPointerException.I generally use a static utility function that I wrote called
equalsWithNulls
to solve this issue:Usage:
Advantages of this approach:
Try using the ObjectUtils class from org.apache.commons.lang
From the api docs...
Compares two objects for equality, where either one or both objects may be null.
ObjectUtils.equals(null, null) = true
ObjectUtils.equals(null, "") = false
ObjectUtils.equals("", null) = false
ObjectUtils.equals("", "") = true
ObjectUtils.equals(Boolean.TRUE, null) = false
ObjectUtils.equals(Boolean.TRUE, "true") = false
ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true
ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false