From 3042fb4592f78562b3c7d007d6377d93c73269c9 Mon Sep 17 00:00:00 2001
From: Dorian Burihabwa Why is this an issue?
boolean Values) it will throw a NullPointerException
if the value is null
(as defined in Java Language Specification §5.1.8 Unboxing Conversion).
It is safer to avoid such conversion altogether and handle the null
value explicitly.
Note, however, that no issues will be raised for Booleans that have already been null-checked.
+Note, however, that no issues will be raised for Booleans that have already been null-checked or are marked @NonNull/@NotNull
.
Boolean b = getBoolean(); @@ -29,6 +29,30 @@+Compliant solution
String test = b ? "test" : ""; }
The issue is not raised if the expression is annotated @NonNull
/ @NotNull
. This is useful if a boxed type is an
+instantiation of a generic type parameter and cannot be avoided.
+List<Boolean> list = new ArrayList<>(); +list.add(true); +list.add(false); +list.forEach((@NonNull Boolean value) -> { + // Compliant + if(value) { + System.out.println("yes"); + } +}); + +@NonNull Boolean someMethod() { /* ... */ } + +// Compliant +if(someMethod()) { /* ... */ } + +@NonNull Boolean boxedNonNull = Boolean.TRUE; + +// Compliant +if(boxedNonNull) { /* ... */ } +