Boolean Object and boolean variable issue in JAVA

后端 未结 6 1746
走了就别回头了
走了就别回头了 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:16

    When you evaluate the boolean value of a Boolean object Java unbox the value (autoboxing feature, since 1.5). So the real code is: dataVal.booleanValue(). Then it throws NullPointerException. With any boxed value, unboxing a null object throws this exception.

    Before 1.5 you had to unbox the value by hand: if (dataVal.booleanValue()) so it was more evident (more verbose too :)

提交回复
热议问题