Attempt to dereference a null object is a very common hard stop which each SFDC developer must have encountered during their development journey. In the beginning, this error proves to be very painful, but once you find a way out of it, it never bothers you again.
This error consists of various phrases which make the statement hard to understand. Let’s segregate and discuss them one by one:
-Pointer (reference and dereference refers to pointers directly or indirectly)
A pointer is an entity which refers to a specific memory address of a variable (In case you don’t know about Pointers, give your search engine a chance!). Every variable has a memory address where the value of that variable resides. Even that address gets stored in a separate variable called Pointer (which is a well-known concept of C language). So, this leads to more memory use and slower running program. Salesforce Apex doesn’t have pointers; it has references. In apex, every variable is a reference itself. Apex doesn’t create two different variables; instead, it creates a table on runtime which returns value directly using references.
a=5; // consider memory address is 137565
b = &a; //& is address operator should return memory address of variable i.e.-137565, but it doesn’t work in apex
Internally apex garbage collector does something like this to store values and references in that table.
Once you have referred to the variable, i.e., pointer, you will be required to fetch the value from it when needed.
c = *b; // * is a dereference operator which should return value of variable i.e.- 5, but it doesn’t work in apex
Internally apex garbage collector does something like this to convert the reference to value or dereference a variable.
Further, this table gets destroyed once these operations are successful and the program ends. The whole concept is the same as pointers, but you can’t do arithmetic on them, they are just for internal garbage collector use only. You see both the phrases seemed easy to read but had a deep meaning.
So, if you are good with the concept now let’s move to the problem with a new article.