Boolean Object and boolean variable issue in JAVA

后端 未结 6 1744
走了就别回头了
走了就别回头了 2020-12-17 08:41

I declare a Boolean variable. For example Boolean dataVal=null;
Now if I execute the following code segment:

if(dataVal)
    System.out.prin         


        
6条回答
  •  独厮守ぢ
    2020-12-17 09:09

    You can have a look at the specification for unboxing issues, your situation is described here section 5.1.8 Unboxing Conversion : If r is null, unboxing conversion throws a NullPointerException

    That means your if ( /* Boolean object */ ) will never be unboxed into a boolean primitive type and therefore throw a NPE because you are doing an invalid if(null).

    By the way, unboxing will work if you had:

    final Boolean booleanTest = new Boolean (true);
    if (booleanTest) {
        // Do something
    }
    

提交回复
热议问题