0

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..

chiperortiz
  • 4,751
  • 9
  • 45
  • 79
  • 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. – Kevin Workman Sep 23 '14 at 13:43
  • Glad you got it sorted out. I was typing the above out as an answer when this was marked as a duplicate, but I figured it wouldn't hurt to post what I had anyway. – Kevin Workman Sep 23 '14 at 13:52
  • 1
    thanks a lot... i am a 8 years java programmer and i never faced it something like this. sorry.. you learn something new everyday best regards from Venezuela... – chiperortiz Sep 23 '14 at 13:57
  • Do not edit you answer to write the solution in the question text. Instead, add an answer (and reverse your question edit). You can mark it as the correct one after 48 hours. – Jan Doggen Sep 23 '14 at 14:10

1 Answers1

1

replace false with Boolean.FALSE and true to Boolean.TRUE

talex
  • 17,973
  • 3
  • 29
  • 66