Java NPE in ternary operator with autoboxing?

前端 未结 5 1214
离开以前
离开以前 2020-12-09 03:29

I ran across a very weird NPE this morning, and reduced it to a simple example. Is this a JVM bug or correct behavior?

public class Test1 {
    class Item {
         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-09 04:09

    It happens because you are using conditional operator ?. Line

    return item == null ? 1 : item.getId();

    is equivalent to

    int result = item == null ? 1 : item.getId();
    return result;
    

    The result is int because of the first operand in your expression. This is the reason that your code works when you explicitly wrap 1 with Integer. In this case the compiler creates something like

    Integer result = item == null ? new Integer(1) : item.getId();
    return result;
    

    So, NPE happens when attempting to "cast" item.getId() (that is null) to int.

提交回复
热议问题