Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

nullpointerexception - Java NPE in ternary operator with autoboxing?

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 {
        Integer id = null;
        public Integer getId() {return id;}
    }   
    public Integer f() {
        Item item = new Item();
        // this works:
        //return item == null ? new Integer(1) : item.getId();

        // NPE??
        return item == null ? 1 : item.getId();
    }   
    public static void main(String[] args) {
        Test1 t = new Test1();
        System.out.println("id is: " + String.valueOf(t.f()));
    }   
}

Output from compile and run:

$ javac Test1.java 
$ java Test1
Exception in thread "main" java.lang.NullPointerException
at Test1.f(Test1.java:12)
at Test1.main(Test1.java:16)
$
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The type of the expression item == null ? 1 : item.getId() is int not Integer. Therefore, Java needs to auto-unbox your Integer to an int (causing the NullPointerException). Then it auto-boxes the result back to an Integer (well it would if not for the NullPointerException) to return from the method.

On the other hand, the expression item == null ? new Integer(1) : item.getId() has a type of Integer and no auto-unboxing needs to be done.

When you auto-unbox a null Integer, you get a NullPointerException (see Autoboxing) and that is what you are experiencing.

To answer your question, this is correct behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...