+ Start a Discussion

How to check whether a field is null or not using Apex class

I am new to Apex. Can anyone help me on this. I want to check whether a field is null or not using Apex classes.
For ex: There is a number field Ratio in custom object Program. Before doing calculations using ratio I just want to check whether ratio is empty.
Below is the code. It's not showing any error,but line numbers 4 and 7 are not covered.
1. Program__c[] pc = [SELECT id,Program_Net_to_Gross_Ratio__c,Labor_Multiplier__c,Labor_Rates__c from Program__c];
2. if(pc.size() > 0)
3. {
4. if(pc[0].Program_Net_to_Gross_Ratio__c != null)
5. pratio = pc[0].Program_Net_to_Gross_Ratio__c;
6. else
7. pratio = 0;
8. }
Vivek ViswanathVivek Viswanath
Try using (!pc.isEmpty()) I know the size is  similar but for me it sometimes gave issues. you are checking for null int he right way at the field level I think I do it similar.
First of all be clear.
are you checking for null or are you checking if the data has not been entered??

so just add a condition more with OR in it
smthn like

|| ==''

i think this shud work!!

Hi Vivek & Iceberg,

Thanks for your valueable suggestions. Let me try it.






Suraj Tripathi 47Suraj Tripathi 47
Hi Shalini,

If I know that my collection is not null because I allocated it or it is the result of a query
then I prefer !.isEmpty() over .size() > 0.

If you find your Solution then mark this as the best answer.    

Thank you!

Suraj Tripathi