Java conditional operator ?: result type

后端 未结 5 1269
忘了有多久
忘了有多久 2020-11-27 17:38

I\'m a bit puzzled about the conditional operator. Consider the following two lines:

Float f1 = false? 1.0f: null;
Float f2 = false? 1.0f: false? 1.0f: null;         


        
5条回答
  •  执念已碎
    2020-11-27 18:11

    It looks like the JVM tries to unbox the second null to float instead of Float, thus NullPointerException. Hit it myself once. My take is that the second if does it because the true part of the first if evaluates as a float, not a Float.

    After giving it a second thought, I think this a way of Java telling you that you are doing something strange. Just don't nest ternary ifs and you will be fine :-)

提交回复
热议问题