使用布尔值 = null 执行条件时出错

Error when doing a condition with a boolean = null

当我尝试这段代码时,我在 Eclipse 上遇到错误

boolean notif = (Boolean) null;
if(notif == null) // <== ERROR at this line saying "No suggestion available" (very helpful)
 {
    System.out.println("Notif = null");
 }

为什么不起作用?

boolean can't be null. It can either be true or false

boolean notif = false;

if(notif)
{
  System.out.println("notif is true");
}
else
{
 System.out.println("notif is false");
}

而对象 Boolean 可以。

boolean是原始类型,它只接受truefalse。如果要将 null 分配给变量,请改用对象 Boolean

Boolean notif = null;

if(notif == null) {
    System.out.println("Notif = null");
}

但是...如果您使用原始类型,请执行以下操作:

boolean notif = // true or false;

if(notif) {
    System.out.println("Notif = true");
}
else {
    System.out.println("Notif = false");
}

编辑: Booleanboolean 之间的区别是第一个是一个对象,它带有一些你可能想要的方法采用。第二个,作为原始类型使用较少的内存。现在考虑这些要点并选择您需要的 ;)

更多关于 Boolean 对象 here 的文档。

当您将 null 转换为“布尔值时,它是包装器 class 而不是原始布尔值。但是当您进行比较时,您是在与预期值为 true 或 false 而不是 null 的原始布尔值进行比较。

您正在尝试获取原始数据类型中所有 null 的值, 相反,您应该使用 Boolean class ,它可以为 null 并且适合您的实现类型。

Boolean notif =  null;
  if( notif == null ) {
      System.out.println("notif is null");
    }  else {
    if(notif){
      System.out.println("notif is true");
    } else {
      System.out.println("notif is false");
    }
}