What is NullPointerException and How to avoid NullPointerException

What is NullPointerException(NPE) ?

NullPointerException is a RuntimeException. In Java, a special null can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference, having the null value. NullPointerException is one of the most common exceptions thrown in Java and programmer face issue with it.

When it occurs:

NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include:

Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.
For example if use below code, it will throw NullPointerException

How to avoid NullPointerException –

When you compare a variable with a string literal, most of people would do that this way:

Always put the string literal first:

Consider Primitives like int, boolean etc, Rather than Objects:

Null problem occurs where object references points to nothing. So it is always safe to use primitives as much as possible because they does not suffer with null references. All primitives have some default values so there will be less chance for NPE.

Use apache commons StringUtils for String operations:

Use apache commons for string operations that contains so many nice functions like isNotEmpty()

Gopal Das
Follow me

Gopal Das

Founder at GopalDas.Org
He is a technology evangelist, Salesforce trainer, blogger, and working as a Salesforce Technical Lead. After working in Java based project implementation, he jumped to the Salesforce system on a whim and never looked back. He fell in love with Salesforce’s flexibility, scalability, and power. He expanded his knowledge of the platform and became a Certified App Builder, Administrator, Platform Developer I, SalesCloud Consultant while leading the Salesforce implementation and technology needs. He has worked in a wide variety of applications/services like desktop, web and mobile applications.
Gopal Das
Follow me

Leave a Reply

Your email address will not be published. Required fields are marked *