[SalesForce] Comparision directly on null value safe

So many times, we do a null check of a field value and then compare them

boolean checkAmountGreaterThan10k(Opportunity record){
    if(record.Amount!=null){
       return record.Amount > 10000;
    }
    return false;
}

Then I recently discovered that any comparison operation performed on null value returns false.

Something like :

Integer bla = null;
System.debug(bla > 10000);//Prints 'false'
System.debug(bla >= 10000);//Prints 'false'
System.debug(bla < 10000);//Prints 'false'
System.debug(bla <= 10000);//Prints 'false'

System.debug( bla + 10000); // throws Null Ptr Exception

Thus I was thinking to use this in the above checkAmountGreaterThan10k as

boolean checkAmountGreaterThan10k(Opportunity record){  
       return record.Amount > 10000;    
}

Is this a documented behavior of comparison operator involving null, I was thinking about saving many lines of code with this.

I came from java world where I used to check null every time, similar java equivalent code throws NullPtrException

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println("Hello World");
        Integer i = null ;
        System.out.println(i < 20); //Exception in thread "main" java.lang.NullPointerException,
    }
}

Java code link:

Is the Apex Runtime not throwing a null ptr exception in Apex a bug or undocumented feature?

Best Answer

I find this behavior documented in the Apex Developer Guide's Expression Operators for the comparison operators:

  • Less than operator
  • Greater than operator
  • Less than or equal to operator
  • Greater than or equal to operator.

If x or y equal null and are Integers, Doubles, Dates, or Datetimes, the expression is false.

Related Topic