this simple code is throwing NPE i dont understand why?
private Boolean isSangByJohnOrPaul()
{
final String sangBy = "harrison";
final Boolean result = sangBy.equals("lennon")?true
:sangBy //throws NPE at this point
.equals("mccartney")?
false
:null;
return result;
}
i think the problem is cause by the primitive type boolean
any workaround.?
thanks a lot
EDIT FIXED
thanks by @Kevin Workman which leads me to this understanding.
This is happening because the type return by a ternary operator is the type of the first returned value. In this case, that's the primitive value false. So Java is trying to take the primitive boolean returned by the ternary operator, then use autoboxing to convert it to a wrapper Boolean. But then you return a null from the ternary operator. And then when Java tries to autobox it, it throws an NPE because null can't be autoboxed. You should either use wrapper Booleans as the values in the ternary operator, or restructure this using if statements.
this works.
private Boolean isSangByJohnOrPaul()
{
final String sangBy = "harrison";
final Boolean result = sangBy.equals("lennon")?Boolean.TRUE
:sangBy
.equals("mccartney")?
Boolean.FALSE
:null;
return result;
}
i hope helps somebody..