I have the following code:
Boolean bool = null;
try
{
if (bool)
{
//DoSomething
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
Why does my check up on the Boolean variable “bool” result in an exception?
Shouldn’t it just jump right past the if statement when it “sees” that it isn’t true?
When I remove the if statement or check up on if it’s NOT null, the exception goes away.
When you have a
booleanit can be eithertrueorfalse. Yet when you have aBooleanit can be eitherBoolean.TRUE,Boolean.FALSEornullas any other object.In your particular case, your
Booleanisnulland theifstatement triggers an implicit conversion tobooleanthat produces theNullPointerException. You may need instead: