Why does Arrays.asList(null) throw a NullPointerException while Arrays.asList(someNullVariable) does not?

Viewed 8645

This small program

public class Client {
    public static void main(String[] args) throws Exception {
        Arrays.asList(null);
    }
}

throws a NullPointerException.

Exception in thread "main" java.lang.NullPointerException
    at java.base/java.util.Objects.requireNonNull(Objects.java:221)
    at java.base/java.util.Arrays$ArrayList.<init>(Arrays.java:4322)
    at java.base/java.util.Arrays.asList(Arrays.java:4309)
    at org.example.Client.main(Client.java:10)

This program, however,

public static void main(String[] args) throws Exception {
    Arrays.asList(returnNull());
}

private static Object returnNull(){
    return null;
}

does not. Why do they behave differently?

2 Answers

The difference is just about how the argument is used at runtime:

The signature of asList is

public static <T> List<T> asList(T... a)

Arrays.asList(returnNull()) calls it with an Object. This clearly does not get interpreted as an array. Java creates an array at runtime and passes it as an array with one null element. This is equivalent to Arrays.asList((Object) null)

However, when you use Arrays.asList(null), the argument that's passed is taken to be an array, and, as the the method explicitly fails on null arrays passed as argument (see java.util.Arrays.ArrayList.ArrayList(E[])), you get that NPE.

Signature of asList() is :- public static <T> List<T> asList(T... a)

So args requires Array of type T.

1st Case: When you put null as arg in asList the array will be pointing to null therefore throwing Exeption.
2nd Case: When you return a reference to any object which is pointing to null. Then it means array having a single Object, and that Object is pointing to null therefore not throwing Exception.

Related