+ Start a Discussion
VKrishVKrish 

Null Pointer Exception when using += addition on numbers

I have a trigger that just counts number of task created with certain values in custom fields.
I am assigning the result in a number field say "num_of_task_with_client"

I am using the following simple addition statement in the code:
        num_of_task_with_client += 1;

which basically means "num_of_task_with_client = num_of_task_with_client + 1;"
when the initial value of the custom field is 0 or blank, I am getting "Attempt to de-reference a null object" error.

But I dont understand why null pointer exception to be thrown on such a basic logical expression.
Why apex is not automatically takeing the blank number value as 0?
Does any one have faced this exception before?
AmitAmit (Salesforce Developers) 
Hello,

You will first have to initialize the variable to function properly.

Please refer following link for more information :

https://developer.salesforce.com/page/Apex_Code_Best_Practices

Thanks,
Amit Bhardwaj


Ramu_SFDCRamu_SFDC
Also remember to always add a condition for null (If xyz!=null){ //do something} Else{ xyz=0 }