Search code examples
javanullpointerexception

A utility method representing, "Both not null and not equal" in Java


String str = "abc";

Comparing this string variable like the following.

if(str.equals("abc")) {}

In case str is null, it will cause a java.lang.NullPointerException to be thrown as obvious.

To avoid that, an additional null check may be enforced. Such as,

if(str != null && str.equals("abc")) {}

I find it plain ugly. Better could be rewritten as follows.

if("abc".equals(str)) {}

This will never throw a java.lang.NullPointerException even though str is null. Besides, object equals null is never true.


The last case however, cannot be used, when the conditional expression is inverted like so,

if(!"abc".equals(str)) {
    System.out.println(str.length());
}

This will cause a java.lang.NullPointerException inside the if block, if str is null.

Can this somehow be avoided without rewriting the conditional statement like the following?

if(str != null && !"abc".equals(str)) {}

This is plain ugly and unreadable.


Although the example uses a String object, it may be a more complex object.


Solution

  • Long story short : There is simply no library method doing this which I know of. This if(str != null && !"abc".equals(str)) {} actually requires that both the objects to be compared are not null and not equal to each other.

    A static utility method performing this task is sufficient to deal with.

    /**
     * Returns {@code true} if and only if both the arguments (objects) are
     * <b>not</b> {@code null} and are not equal to each other and {@code false}
     * otherwise.
     *
     * @param a an object.
     * @param b an object to be compared with {@code a} for equality.
     * @return {@code true} if both the arguments (objects) are <b>not</b> {@code null}
     * and not equal to each other.
     */
    public static boolean notEquals(Object a, Object b) {
        return (a == b || a == null || b == null) ? false : !a.equals(b);
    }