Strange Java behaviour. Ternary operator

…衆ロ難τιáo~ 提交于 2019-11-26 07:42:55

问题


Why does this code work?

Float testFloat = null;
Float f = true ? null : 0f;

And why does this throw an exception?

Float testFloat = null;
Float f = true ? testFloat : 0f;

But the strangest thing is that this code also runs successfully without any exceptions:

Float testFloat = null;
Float f = testFloat;

It seems that the ternary operator of Java changes the behaviour. Can anyone explain why this is, please?


回答1:


The behaviour is specified in JLS - Conditional Operator:

If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

Emphasis mine. So, in the 2nd case:

Float f = true ? testFloat : 0f;

Since 3rd operand is primitive type(T), the type of the expression would be float type - T. So, unboxing testFloat which is currently a null reference, to float will result in NPE.


As for the 1st case, relevant part is the last one:

Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2. The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7).

So, according to this:

null type - S1
float     - S2

null type - T1 (boxing null type gives null type)
Float     - T2 (float boxed to Float)

and then type of conditional expression becomes - Float. No unboxing of null needed, and hence no NPE.



来源:https://stackoverflow.com/questions/17934526/strange-java-behaviour-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!