Ternary Operator vs. if Statement for Null Return of int
In Java, the ternary operator (?:) allows for the assignment of null to a variable of type int, even though int is a primitive data type that does not support null values. Consider the following code snippet:
<code class="java">int temp() { return true ? null : 0; }</code>
In this code, the ternary operator assigns null to the variable temp if true is the evaluated condition, otherwise it assigns 0. The compiler allows this assignment without issuing any errors. However, when the method is executed, it will throw a NullPointerException at runtime because null is not a valid value for int.
In contrast to the ternary operator, the if statement does not allow such null assignments to variables of primitive types. For example:
<code class="java">int same() { if (true) { return null; } else { return 0; } }</code>
This code will generate a compile-time error with the message "incompatible types: null cannot be converted to int." The reason for this discrepancy lies in the way the compiler treats the value null.
In the case of the ternary operator, the compiler interprets the null literal as a null reference to an Integer, the wrapper class for int. This is due to compiler rules for autoboxing and unboxing: when converting from a primitive type to an object type, the Java Virtual Machine (JVM) automatically wraps the primitive value in the corresponding object wrapper.
Since int is a primitive type, the compiler will attempt to unbox the null value returned by the ternary operator, which results in the NullPointerException.
On the other hand, the if statement does not perform this unboxing process, and the null literal remains as a null reference to Object. Since the return type of the same() method is int, the compiler cannot convert the null reference to int, hence the compile-time error.
The above is the detailed content of Why Does the Ternary Operator Allow Null Return for int While an if Statement Doesn't?. For more information, please follow other related articles on the PHP Chinese website!