Home  >  Article  >  Java  >  Why Does the Ternary Operator Allow Null While the If Statement Does Not?

Why Does the Ternary Operator Allow Null While the If Statement Does Not?

Linda Hamilton
Linda HamiltonOriginal
2024-11-04 18:04:01810browse

Why Does the Ternary Operator Allow Null While the If Statement Does Not?

NullPointerException in Java: Ternary Operator vs. If Statement

Consider the following Java code snippet:

<code class="java">public class Main {

    private int temp() {
        return true ? null : 0; // No compiler error
    }

    private int same() {
        if (true) {
            return null; // Compile-time error
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        Main m = new Main();
        System.out.println(m.temp());
        System.out.println(m.same());
    }
}</code>

Question: Why does the temp() method (using a ternary operator) not produce a compiler error, while the same() method (using an if statement) does?

Answer: The Java compiler interprets null as a null reference to an Integer. When using the conditional operator, autoboxing/unboxing rules are applied (as per the Java Language Specification, 15.25). This allows the compiler to proceed without issuing an error, even though a NullPointerException will be thrown at run time.

In contrast, when using an if statement, the compiler applies standard type checking rules. Since null is not a valid int value, a compile-time error is produced.

The above is the detailed content of Why Does the Ternary Operator Allow Null While the If Statement Does Not?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn