Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ternary conditions strange null pointer exception [duplicate]

Can someone explain me why in the first case null pointer was detected, but no on the other ?

Maybe he always looks on the first type, but why he does so only if the condition is false..

@Test
public void test1() {
    final Integer a = null;

    final Integer b = false ? 0 : a;

    //===> NULL POINTER EXCEPTION
}

@Test
public void test2() {
    final Integer b = false ? 0 : null;

    //===>NOT NULL POINTER EXCEPTION
}

@Test
public void test3() {
    final Integer a = null;

    final Integer b = true ? 0 : a;

    //===>NOT NULL POINTER EXCEPTION
}

@Test
public void test4() {
    final Integer a = null;

    final Integer b = false ? new Integer(0) : a;

    //===> NOT NULL POINTER EXCEPTION
}

@Test
public void test5() {
    final Integer a = null;

    final Integer b = false ? a : 0;

    //===>NOT NULL POINTER EXCEPTION
}
like image 468
Kimo_do Avatar asked Jun 29 '16 09:06

Kimo_do


2 Answers

When you use ternary operator,

 flag  ? type1 : type2

Type1 and type2 must be of same type while conversion. First it realises type1 and then type2.

Now look at your cases

 final Integer b = false ? 0 : a;

Since type1 is 0 and it takes as a primitive and since a is trying to convert it as a primitive. Hence the null pointer.

where as same tricky test5

 final Integer b = false ? a : 0;

Since a is of type Integer 0 boxed to wrapper integer and assigned to the LHS.

like image 101
Suresh Atta Avatar answered Nov 15 '22 04:11

Suresh Atta


I think in this case a will unboxed to an int, because 0 is an int . That means that null.intValue() is called and get an NPE

@Test
public void test1() {
    final Integer a = null;

    final Integer b = false ? 0 : a;
like image 28
Jens Avatar answered Nov 15 '22 03:11

Jens