Java trernary conditions weird null pointer exception

Can someone explain to me why in the first case a null pointer was found, but there is no other?

Maybe he always looks at the first type, but why does he do it 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
}
+4
source share
2 answers

When using the triple operator

 flag  ? type1 : type2

Type1 and type2 must be of the same type during conversion. It implements type1 first, and then type2.

Now look at your cases

 final Integer b = false ? 0 : a;

As it type1is 0, and it takes as a primitive, and since atrying to transform it as primitive. Hence the null pointer.

where is the same difficult test5

 final Integer b = false ? a : 0;

a Integer 0, LHS.

+4

, a int, 0 int. , null.intValue() NPE

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

    final Integer b = false ? 0 : a;
+3

All Articles