nullpointerexception - java ternary conditions strange null pointer exception -


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

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -