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!