Search code examples
javanullpointerexceptionbigdecimal

handling Null for bigdecimal


My code looks like below,

caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);

if(caseXObj != null && caseXObj.getCaseInGrossAmt() != null){

} else {
    caseXObj.setCaseAmt(BigDecimal.ZERO);
}

I have handled NUll pointer for the caseX and also for getter and when null set the bigdeciaml to a default ZERO value. Still I get Null pointer exception in the setter line.Any suggestions?


Solution

  • It's quite possible that caseXObj is null, so it'll cause the NullPointerException. You should test the three cases like this:

    caseX caseXObj = caseXBo.getCaseXDao().findCaseXBySID(selectedID);
    if (caseXObj != null && caseXObj.getCaseInGrossAmt() != null) {
        // do something with caseXObj 
    } else if (caseXObj == null) {
        // initialize caseXObj, you were misssing this case!
    } else {
        caseXObj.setCaseAmt(BigDecimal.ZERO);
    }
    

    In essence, the error was that you were testing for only two cases - and there are three of them.