Java – why return null (Boolean value required) as the result of ternary operator compilation?

See English answers > Booleans, conditional operators and autoboxing

I'm not allowed to write

public boolean x() {
  return null;
}

Or this:

public boolean x() {
  if (DEBUG) {
    return true;
  } else {
    return null;
  }
}

But I was allowed to write

public boolean x() {
  return DEBUG ? true : null;
}

Why? (if you take the "else" branch, it seems to throw NPE.)

Solution

As JLS said:

This means that Java allows nulls because it can be used to generate instances of Boolean and unpack them as Boolean (for more information, please read the section on boxing in JLS) However, since the Boolean instance is initialized to null, the call to Boolean value() will result in NullPointerException

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>