What is NullPointerException in Java, and how to avoid and fix it?

In Java NullPointerExceptions are exceptions that occur when we try to use a reference that points to no location in memory (Know as null) as though it were referencing an object (uninitialized objects or assigned to null object references). Calling a method or accessing a member on a null reference will throw a NullPointerException.

Generally, in Java, the class Object defines the behavior of all Java objects. Actually, it does not, however, define the behavior of all Java data structures. That is, because, not all Java data structures are objects. Some of them are primitive values that can be stored in object variables but are not objects themselves. Primitive types should be distinguished from Java interfaces or classes, which are object types.

A primitive data type uses a small amount of memory to represent a single item of data. All data of the same primitive type are the same size.

For example, primitive type int represents integers using 32 bits. All variables of type int use 32 bits.

There are only eight primitive data types in Java: byte, short, int, long, float, double, char, and boolean. A Java program cannot define any other primitive data types.

For each primitive type, Java defines a wrapper class, which stores a value of the primitive type as an instance variable, and provides methods to initialize and read that value. Thus, it provides the wrapper class Integer, which wraps an object around a value of type int and it is a reference type. The constructor of Integer is:

public Integer(int value);

Consider the following code where you declare a variable of primitive type int:

int x;
x = 10;

In this example, the variable x is an int and Java will initialize it to 0 for you. When you assign it to 10 in the second line your value 10 is written into the memory location pointed to by x.

But, when you try to declare a reference type something different happens. Take the following code:

Integer num;
num = new Integer(10);

The first line declares a variable named num, but, it does not contain a primitive value. Instead, it contains a pointer (because the type is Integer which is a reference type). Since you did not say as yet what to point to Java sets it to null, meaning “I am pointing at nothing”.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer and the pointer variable num is assigned this object. You can now reference the object using the dereferencing operator. (a dot).

If you attempt to dereference num BEFORE creating the object using new you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that “num may not have been initialized” but sometimes you write code that does not directly create the object.

For example, you may have a method as follows:

public void someMethod(SomeObject obj) {
//do something to obj
}

Unfortunately, it is possible to call the method like this, calling a method with null parameter value:

someMethod(null);

In the above case, obj is null. If the method is intended to do something to the passed-in object, it will throw the NullPointerException.

How to avoid NullPointerException in java?

Best way to avoid NullPointerException is to always check for null when you did not create the object, or getting an object from some method call as a result or getting this as a parameter in the method.

To avoid this you may need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething could be written as:

public void someMethod(SomeObject obj) {
if(obj != null) {
//do something
} else {
//do something else
}
}

Some best practices to avoid NULL Pointer exception

  • Use the final modifier to enforce good initialization.
  • Avoid returning null in methods, for example returning empty collections when applicable.
  • Use annotations @NotNull and @Nullable
  • Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn’t be null.
  • Use equals with a known object first: if(“knownObject”.equals(unknownObject)
  • Prefer valueOf() over toString().
  • Use null safe StringUtils methods StringUtils.isEmpty(null).

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.