Check if null Boolean is true results in exception

后端 未结 7 1348
难免孤独
难免孤独 2020-11-28 05:20

I have the following code:

Boolean bool = null;

try 
{
    if (bool)
    {
        //DoSomething
    }                   
} 
catch (Exception e) 
{
    Syst         


        
相关标签:
7条回答
  • 2020-11-28 05:51

    Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.

    The wrapper classes in the Java API serve two primary purposes:

    1. To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
    2. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

    http://en.wikipedia.org/wiki/Primitive_wrapper_class

    0 讨论(0)
  • 2020-11-28 05:52

    Boolean types can be null. You need to do a null check as you have set it to null.

    if (bool != null && bool)
    {
      //DoSomething
    }                   
    
    0 讨论(0)
  • 2020-11-28 05:53

    as your variable bool is pointing to a null, you will always get a NullPointerException, you need to initialize the variable first somewhere with a not null value, and then modify it.

    0 讨论(0)
  • 2020-11-28 05:55

    When you have a boolean it can be either true or false. Yet when you have a Boolean it can be either Boolean.TRUE, Boolean.FALSE or null as any other object.

    In your particular case, your Boolean is null and the if statement triggers an implicit conversion to boolean that produces the NullPointerException. You may need instead:

    if(bool != null && bool) { ... }
    
    0 讨论(0)
  • 2020-11-28 05:55

    Or with the power of Java 8 Optional, you also can do such trick:

    Optional.ofNullable(boolValue).orElse(false)
    

    :)

    0 讨论(0)
  • 2020-11-28 05:58

    If you don't like extra null checks:

    if (Boolean.TRUE.equals(value)) {...}
    
    0 讨论(0)
提交回复
热议问题