Based on the concept we cleared in the previous blog (please read Part 1 of this blog to get a more clear idea) There are two scenarios possible where Attempt to dereference error can occur.

– When your object is not initialized

– When your object has null values

Cause 1: When your variable is not initialized, your reference table won’t be having a value for the reference you are searching for, so it will return this error which means that no memory allocation was done for the variable.

For Example:

Account accObj; // declaration part

System.debug(accObj); // it will return null as it has no value – it is a kind of soft stop by the apex

System.debug(accObj.name); // it will return Attempt to dereference null object error – hard stop

You are trying to access a sub-element or a field of account when there is no account given. You can think of this statement as null.name, but does it make sense? Nope. Similarly, apex also doesn’t understand this and reports this confusion as an error.

In this case, the solution is simple. You can do a memory allocation in apex using the New keyword.

For Example:

Account accObj = new Account(); // declaration and initialization part

system.debug(accObj); // it will return Account:{} which means it have memory and ready to accept values

system.debug(accObj.name); // it will return null as it has no value – soft stop

Once you allocated memory using the new keyword, your reference table will start returning memory addresses so that this error won’t occur anytime. However, the value returned will be “null” which implies that the variable gets allotted with memory, but memory still doesn’t process any value.

Isn’t it interesting? Check out the next Blog for Part 3 of Attempt to de-reference a null object.