adplus-dvertising

Why does this line produce a nullpointer? Java 15

Asked 3 months ago
Viewed 19 times

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

The error only happens in Java Version 15. Could you please tell me why this happens?

asked 3 months ago

Correct Answer

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 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

answered 3 months ago