简体   繁体   中英

Comparing the value of two null objects without NPE

This is an extremely basic question but why is the following code returning a null pointer exception?

String a = null;
String b = null;

System.out.println(a.equals(b));

According to the docs here:

http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals(java.lang.Object,%20java.lang.Object)

the .equals() function is first checking for null before comparing values. Shouldn't it return true since they are both null?

The method you linked to takes in two objects and is a static method. You need to call it like Objects.equals(a, b) . Instead you are calling .equals() on a null object which throws NPE

Shouldn't it return true since they are both null?

nop. since a is a null-referenced object, invoking ANY instance method on that object will throw a NPE

so what you can do:

if you are still on java 6 do

System.out.println(a == null ? b == null : a.equals(b));

and since java 7

System.out.println(Objects.equals(a, b));

I usually write following method,

private boolean equalsWithNull(String first, String second){
    return ((first!=null&&second!=null && first.equals(second)) || (first==null && second==null));
}

Objects::equals is the best option, but you can use

Optional.ofNullable(a).equals(Optional.ofNullable(b))

as well. However I don't really see any cases when you will choose Optional approach instead of Objects

you can check both values instead of reference,

        String a = null;
        String b = null;
        System.out.println(a == b ? "true":"false");

it returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM