Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does returning null (where a boolean is expected) as the result of a ternary operator compile? [duplicate]

A curiosity that I've just noticed, rather than a problem.

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 am allowed to write

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

Why is this? (It appears to throw an NPE if the "else" branch is taken.)

like image 249
Michael Kay Avatar asked Aug 28 '15 07:08

Michael Kay


People also ask

Can you return null in a Boolean?

Null should not be returned from a "Boolean" method.

What does ternary operator return?

The ternary operator evaluates to see if a randomly generated number is less than zero. If the number is less than zero, the condition is true and the text String “negative” is returned. If the number is greater than zero, the condition is false and the text String “positive” is returned.

How to check null in ternary operator Java?

parseInt(input); Notice how the first ternary operator condition checks if the input String is null . If so, the first ternary operator returns 0 immediately. If the input String is not null , the first ternary operator returns the value of the second ternary operator.

How do ternary operators work Java?

Ternary Operator in Java A ternary operator evaluates the test condition and executes a block of code based on the result of the condition. if condition is true , expression1 is executed. And, if condition is false , expression2 is executed.


1 Answers

As the jls states:

The type of a conditional expression is determined as follows: If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression. If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

This means java allows null, since it can be used to generate an instance of Boolean, which can be unboxed to boolean (read the section about boxing in the jls for more info). But since the Boolean instance is initialized null, the call to booleanValue() will result in a NullPointerException.

like image 132
Paul Avatar answered Sep 21 '22 10:09

Paul