By koushlendra

2019-06-11 15:20:36 8 Comments

This small program

public class Client {
    public static void main(String[] args) throws Exception {

throws a NullPointerException.

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

This program, however,

public static void main(String[] args) throws Exception {

private static Object returnNull(){
    return null;

does not. Why do they behave differently?


@Tarun 2019-06-11 15:45:47

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.

@ernest_k 2019-06-11 15:34:16

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.

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] Why does this code using random strings print "hello world"?

  • 2013-03-03 04:38:06
  • 0x56794E
  • 192738 View
  • 1718 Score
  • 15 Answer
  • Tags:   java string random

13 Answered Questions

[SOLVED] Why does Java have transient fields?

  • 2009-05-26 12:11:36
  • Animesh
  • 659596 View
  • 1372 Score
  • 13 Answer
  • Tags:   java field transient

3 Answered Questions

[SOLVED] java exception - why does it catch?

  • 2018-12-18 20:27:00
  • Marius Donici
  • 154 View
  • 0 Score
  • 3 Answer
  • Tags:   java exception

0 Answered Questions

26 Answered Questions

1 Answered Questions

[SOLVED] Why reading byte array to an Object throws

  • 2014-04-15 05:03:19
  • Niranjan
  • 1915 View
  • -1 Score
  • 1 Answer
  • Tags:   java

0 Answered Questions

without main class in java throws error while running

  • 2018-03-14 15:58:27
  • Mohammed Ismail A
  • 72 View
  • 2 Score
  • 0 Answer
  • Tags:   java

1 Answered Questions

KAFKA Java consumer not working

2 Answered Questions

[SOLVED] Does it make sense to throw a private exception?

Sponsored Content