Search code examples
javaandroidexceptionnullpointerexception

Avoiding NullPointerException from Boolean


I am trying to avoid a NullPointerException from a Boolean. I thought with the code below will work but it's not.

if(Boolean.TRUE.equals(shareConnection.getConnection())){ // This could be null, True or False

}

any ideas? I don't want to implement a try catch statement because this is already inside a catch.

Edit

public class ShareConnection{

    public boolean getConnection() {
        return connection;
    }
}

Solution

  • if(Boolean.TRUE.equals(shareConnection.getConnection()))
    

    The only way for NPE here is:

    • shareConnection is null

    Use a Debugger to analyze your program state.