Why does this line produce a nullpointer? Java 15

Advertisements

The following two lines:

   Boolean visitedAlphabet[] = new Boolean[26];
   Arrays.stream(visitedAlphabet).anyMatch(e -> e != true);

Produce a nullpointer, the second line to be specific:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because "<parameter1>" is null

Could you please tell me why this happens?

>Solution :

EDIT – Adding John Bollinger’s excellent comment snipped –

Because e is null and the runtime is trying to "unbox" it to a primitive boolean.

You can either do (e != null && e != true) or !Boolean.TRUE.equals(e) or initialize your array:

Initialize an array stuff:

How to initialize an array in Java?

Boxing and unboxing:

https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

Leave a ReplyCancel reply