Conversion from null to int possible?

前端 未结 6 1942
刺人心
刺人心 2020-12-08 02:05

I know that when I read the answer to this I will see that I have overlooked something that was under my eyes. But I have spent the last 30 minutes trying to figure it out m

6条回答
  •  无人及你
    2020-12-08 02:28

    Let's look at the line:

    return y == null ? null : y.intValue();
    

    In a ? : statement, both sides of the : must have the same type. In this case, Java is going to make it have the type Integer. An Integer can be null, so the left side is ok. The expression y.intValue() is of type int, but Java is going to auto-box this to Integer (note, you could just as well have written y which would have saved you this autobox).

    Now, the result has to be unboxed again to int, because the return type of the method is int. If you unbox an Integer that is null, you get a NullPointerException.

    Note: Paragraph 15.25 of the Java Language Specification explains the exact rules for type conversions with regard to the ? : conditional operator.

提交回复
热议问题