Java NPE in ternary operator with autoboxing?

前端 未结 5 1212
离开以前
离开以前 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条回答
  •  Happy的楠姐
    2020-12-09 03:59

    The return type below is Integer -

    public Integer f() {
        Item item = new Item();
        // this works:
        //return item == null ? new Integer(1) : item.getId();
    
        // NPE??
        return item == null ? 1 : item.getId();
    }
    

    And the result of the following -

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

    is null in your case.

    So, JVM is throwing NPE because it is trying to autobox null.

    Try -

    new Integer(null); // and
    Integer.valueOf(null);
    

    both will throw NPE.

提交回复
热议问题