nullpointerexception - java ternary conditions strange null pointer exception -
this question has answer here:
can explain me why in first case null pointer detected, no on other ?
maybe looks on first type, why if condition false..
@test public void test1() { final integer = 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 = null; final integer b = true ? 0 : a; //===>not null pointer exception } @test public void test4() { final integer = null; final integer b = false ? new integer(0) : a; //===> not null pointer exception } @test public void test5() { final integer = null; final integer b = false ? : 0; //===>not null pointer exception }
when use ternary operator,
flag ? type1 : type2
type1 , type2 must of same type while conversion. first realises type1 , type2.
now @ cases
final integer b = false ? 0 : a;
since type1
0
, takes primitive , since a
trying convert primitive
. hence null pointer.
where same tricky test5
final integer b = false ? : 0;
since of type integer
0 boxed wrapper integer , assigned lhs.
Comments
Post a Comment