I was trying to fix a null pointer exception here

if(com.Employee__c != null && (mapEmployees.containskey(com.Employee__c) == null || (mapEmployees.containskey(com.Employee__c) != null && mapEmployees.get(com.Employee__c).Employee_End_Date__c > com.Revenue_Contract_Start_Date__c)))

as mapEmployees.get(com.Employee__c).Employee_End_Date__c

was null here so replaced this block with

if(com.Employee__c != null && (mapEmployees.containskey(com.Employee__c) == null ||
                            (mapEmployees.containskey(com.Employee__c) != null && ((mapEmployees.get(com.Employee__c).Employee_End_Date__c == null) || (
                                mapEmployees.get(com.Employee__c).Employee_End_Date__c!=null && mapEmployees.get(com.Employee__c).Employee_End_Date__c > com.Revenue_Contract_Start_Date__c)))))

But I am still getting the Null Pointer exception at this line (mapEmployees.get(com.Employee__c).Employee_End_Date__c == null)

1 Answer 1


Map.containsKey always returns a true or false value, but never a null value. As such:

mapEmployees.containskey(com.Employee__c) == null 

(true or false) == null

((always false!))


mapEmployees.containskey(com.Employee__c) != null

(true or false) != null

((always true!))

And therefore will keep on going through the shortcut AND operator. True or false will never be null, so the first will never pass, and the latter will never fail.

This means that:


will throw a NullPointerException if mapEmployees.containskey(com.Employee__c) returned false (because the == null will change this to true, and the code keeps going when it shouldn't).

By the way, this really over-the-top logic checking, you usually only care of the value itself was null. The following should suffice:

User employee = mapEmployees.get(com.Employee__c);
if(employee != null && (
    employee.Employee_End_Date__c == null || 
    employee.Revenue_Contract_Start_Date__c == null || 
    employee.Employee_End_Date__c > employee.Revenue_Contract_Start_Date__c)) {

I'm not entirely sure your logic is correct, so this is my best attempt at trying to decipher what you're trying to do, but you can see that simply extracting the map value to a temporary variable has drastically reduced the complexity of your code and makes it easier to understand. This code is also 100% NullPointerException-proof as written.

  • Thanks, @sfdcfox This helped me understand the problem with my code.
    – Ishan
    Commented May 27, 2020 at 3:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .