I am trying to validate for NULLs on a data type BigDecimal in java. I am able to validate for 0 value however NULL's is resulting in a NULL Point Exception. Should I handle the validation of this datatype in an exception or is there some calculation I can preform on the data to validate it. Under is an example of what i have done so far:
if(crime.getCrimeLatLocation() != null & crime.getCrimeLongLocation() != null || crime.getCrimeLatLocation().compareTo(BigDecimal.ZERO) != 0 & crime.getCrimeLongLocation().compareTo(BigDecimal.ZERO) != 0){
logger.info('Valid Data');
}
Your ||
should be an &&
- what's happening is that when you pass in a null value it's evaluating to false in the first two conditions, but then it's proceeding on to the third and fourth conditions and resulting in an exception. If you change the ||
to an &&
then short circuit evaluation will prevent the third and fourth conditions from evaluating.
Be certain to use a &&
and not a &
- the former uses short-circuit evaluation, but the latter would force the third and fourth conditions to evaluate and you'll get a null pointer exception again. condition1 && condition2
says "return false if condition1 is false, else evaluate condition2" - if condition1 is false then condition2 is never evaluated. In contrast, condition1 & condition2
will always evaluate both conditions. The only reason to use &
is if the conditions have side-effects. Likewise, condition1 || condition2
will not evaluate condition2 if condition1 is true, but |
will always evaluate both conditions.