Very strange behavior of Java (bug?)

Hi

The following code always throws a NullPointerException:

public static void main(String[] args) {
        getInt(true);
    }
    
    public static int getInt(boolean b) {
        return b?null:0;
    }

I don’t understand why it is considered valid by the compiler. If I try to always return null, it does not compile. I don’t use autoboxing, I have just found this kind of code in the source code of someone else.

How does it work in Java 1.7? I still use Java 1.6.

Edit.: I use the OpenJDK.

I’m probably wrong but shouldn’t you not be able to return null? I didn’t think you could return it in place of a primative variable. I don’t know why you’d want to anyway.

Isn’t this exactly what it’s trying to do? Unbox a null Integer into an int, which fails?

EDIT: try Googling “autoboxing ternary operator” - there’s a few things about this.

Just one of those crazy reasons why autoboxing should be used with care.

Cas :slight_smile:

You’re right, the compiler refuses it, I cannot do the same without the ternary operator.

This is not my source code. Thanks for the tip.

In my humble opinion, it should not be used at all.