Weird behaviour when using Java ternary operator

后端 未结 3 2321
误落风尘
误落风尘 2021-02-19 20:49

When I write my java code like this:

Map map = new HashMap<>()
Long number =null;
if(map == null)
    number = (long) 0;
else
    numbe         


        
3条回答
  •  孤独总比滥情好
    2021-02-19 21:50

    What is happening here? Both these code paths are exactly equivalent isn't it?

    They are not equivalent; the ternary operator has a few caveats.

    The if-true argument of the ternary operator, (long) 0, is of the primitive type long. Consequently, the if-false argument will be automatically unboxed from Long to long (as per JLS §15.25):

    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.

    However, this argument is null (since your map does not contain the string "non-existent key", meaning get() returns null), so a NullPointerException occurs during the unboxing process.

提交回复
热议问题