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:
int temp() {
return true ? null : 0;
}
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:
int same() {
if (true) {
return null;
} else {
return 0;
}
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3