Java: NullPointerException when assigned to null Boolean

When I tried to assign a null Boolean as shown below, I have a NullPointerException.

String strA = "something neither true nor false";
Boolean a = "true".equals(strA) ? true : "false".equals(strA) ? false : null;

      

I don't know why this happens when other cases like below work.

Boolean a = null;
Boolean a = "true".equals(strA) ? true : null;

      

+3


source to share


1 answer


I believe this is a boxing / unboxing issue. Appointment Boolean.TRUE

or Boolean.FALSE

:

Boolean a = "true".equals(strA) 
             ? Boolean.TRUE 
             : ("false".equals(strA) ? Boolean.FALSE : null);

      



works as expected.

+2


source







All Articles