Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...