2022-12-12 09:38:58 +01:00
When boxed type `java.lang.Boolean` is used as an expression to determine the control flow (as described in https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.5[Java Language Specification §4.2.5 The `boolean` Type and boolean Values]) it will throw a `NullPointerException` if the value is `null` (as defined in https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8[Java Language Specification §5.1.8 Unboxing Conversion]).
2021-04-28 16:49:39 +02:00
2022-12-12 09:38:58 +01:00
It is safer to avoid such conversion altogether and handle the `null` value explicitly.
2021-04-28 16:49:39 +02:00
2022-12-06 15:54:00 +01:00
Note, however, that no issues will be raised for Booleans that have already been null-checked.
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Boolean b = getBoolean();
if (b) { // Noncompliant, it will throw NPE when b == null
foo();
} else {
bar();
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
2022-12-12 09:38:58 +01:00
foo();
2021-04-28 16:49:39 +02:00
} else {
bar(); // will be invoked for both b == false and b == null
}
2022-12-13 15:44:26 +01:00
2022-12-06 15:54:00 +01:00
Boolean b = getBoolean();
if(b != null){
String test = b ? "test" : "";
}
----
2021-04-28 18:08:03 +02:00
2021-04-28 16:49:39 +02:00
== See
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8[Java Language Specification §5.1.8 Unboxing Conversion]
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]