Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

Have you Noticed java.lang.NullPointerException (NPE)? 8 Best Practices to Avoid runtime NPE in Java

$
0
0

avoid-null-pointer-exception-npe-crunchify-tips

Avoid Null Pointer Exception in Java and Java Tips and Best practices to avoid NullPointerException in Java.

As a Java Developer, I’m sure you must have faced Null Pointer Exception (NPE) starting 1st day. In most of the cases NPE exception shows clear stack trace which pin points the root cause of the same but in case of large Enterprise level Application in which you have hundreds of classes, it becomes nightmare to find out real root cause.

What is NPE?

NullPointerException (NPE) is an exception that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NPE. This is the most common cause.

As per JavaDoc, below are the major causes for NPE:

  • Throwing null as if it were a Throwable value.
  • 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.

Now real question is How to Avoid java.lang.NullPointerException at Runtime? In this tutorial we will look at few examples which creates NPE at runtime and steps we need to perform in order to resolve this.

Let’s create NPE at runtime 1st. Take a look at below example CrunchifyNullPointerExceptionTips.java

We will create NPE 3 different ways

  1. NPE will be thrown if you are trying to access null Object
  2. NPE will be thrown if you are trying to convert null String
  3. NPE will be thrown if you are trying to access null Object during class initialization

package com.crunchify.tutorial;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyNullPointerExceptionTips {
	public static void main(String[] args) {
		try {
			// Example 1: NPE will be thrown if you are trying to access null Object
			CrunchifyNPE1();
		} catch (NullPointerException npe1) {
			System.out.println("Exception in CrunchifyNPE1()");
			npe1.printStackTrace();
		}

		try {
			// Example 2: NPE will be thrown if you are trying to convert null String
			CrunchifyNPE2();
		} catch (NullPointerException npe2) {
			System.out.println("\nException in CrunchifyNPE2()");
			npe2.printStackTrace();
		}

		try {
			// Example 3: NPE will be thrown if you are trying to access null Object during Class Initialization
			CrunchifyNPETest npe = new CrunchifyNPETest();
			npe.getName();
		} catch (NullPointerException npe3) {
			System.out.println("\n Exception in CrunchifyNPETest()");
			npe3.printStackTrace();
		}

	}

	private static void CrunchifyNPE1() {
		Object crunchifyObj = null;
		crunchifyObj.hashCode();
	}

	private static void CrunchifyNPE2() {
		String crunchifyString;
		crunchifyString = "http://crunchify.com";
		// The line 40 declares a variable named "crunchifyString", but, it does not contain a primitive value. Instead it contains a pointer (because the type
		// is String
		// 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 line 41, the new keyword is used to instantiate (or create) an object of type String and the pointer variable "crunchifyString" is assigned this
		// object. You can now reference the object using the dereferencing operator . (a dot).

		System.out.println("\nvalue: " + crunchifyString.toString() + ", lenght: " + crunchifyString.length());
		System.out.println("No NPE exception on line 51");

		// Now Let's create NPE
		String crunchifyString2 = null;
		System.out.println(crunchifyString2.toString());

	}
}

class CrunchifyNPETest {
	private String crunchifyName;

	public void setName(String name) {
		this.crunchifyName = name;
	}

	public void getName() {
		printName(crunchifyName);
	}

	private void printName(String s) {
		System.out.println(s + " (" + s.length() + ")");
	}
}

Result:

Exception in CrunchifyNPE1()
java.lang.NullPointerException
	at com.crunchify.tutorial.CrunchifyNullPointerExceptionTips.CrunchifyNPE1(CrunchifyNullPointerExceptionTips.java:39)
	at com.crunchify.tutorial.CrunchifyNullPointerExceptionTips.main(CrunchifyNullPointerExceptionTips.java:12)

value: http://crunchify.com, lenght: 20
No NPE exception on line 51

Exception in CrunchifyNPE2()
java.lang.NullPointerException
	at com.crunchify.tutorial.CrunchifyNullPointerExceptionTips.CrunchifyNPE2(CrunchifyNullPointerExceptionTips.java:56)
	at com.crunchify.tutorial.CrunchifyNullPointerExceptionTips.main(CrunchifyNullPointerExceptionTips.java:20)

 Exception in CrunchifyNPETest()
java.lang.NullPointerException
	at com.crunchify.tutorial.CrunchifyNPETest.printName(CrunchifyNullPointerExceptionTips.java:73)
	at com.crunchify.tutorial.CrunchifyNPETest.getName(CrunchifyNullPointerExceptionTips.java:69)
	at com.crunchify.tutorial.CrunchifyNullPointerExceptionTips.main(CrunchifyNullPointerExceptionTips.java:29)

Well, there are few tips and tricks we could use to avoid NullPointerException at runtime. Let’s take a look.

Hint 1:

Eclipse / IntelliJ IDE will try to show NPE in workspace. Correct your code during development only.

Null Pointer Hint in Eclipse

Hint 2:

Add crunchifyIsNullorEmpty() check before an operation on object. Add this to CrunchifyNullPointerExceptionTips.java

public static boolean crunchifyIsNullOrEmpty(String crunchifyStr) {
	if (crunchifyStr == null)
		return true;
	else if (crunchifyStr.trim().equals(""))
		return true;
	else
		return false;
}

In above java program line 55 and 56 will be replaced with this.

String crunchifyString2 = null;
if (!crunchifyIsNullOrEmpty(crunchifyString2)) {
	System.out.println(crunchifyString2.toString());
} else {
	System.out.println("crunchifyString2 is null");
}

Hint 3:

Check if String is null of empty after trim() operation.

public static boolean isNullOrEmptyAfterTrim(String crunchifyStr) {
        return (crunchifyStr == null || crunchifyStr.trim().length() == 0);
}

Hint 4:

Always use Try Catch block in order to prevent uninterrupted Runtime Process.

try {
	CrunchifyNPE1();
} catch (NullPointerException npe) {
	System.out.println("Exception in CrunchifyNPE1()" + npe);
}

Hint 5:

Collections.emptyList() is preferred due to better handling of generics.

Hint 6:

Use Java Assertions

An assertion is a statement that enables you to test your assumptions about your code. For example, if you write a method that returns the name in the system, you might assert that the returning otherName if String is null. Basic usage of assertions would be:

assert <Expression>; // or another usage is
assert <Expression1> : <Expression2>;

// in our program add line below.
private void printName(String s) {
	assert (s != null) : "Name must be not null"; 
	System.out.println(s + " (" + s.length() + ")");
}

But there is a catch: Assertion is not available in production environment and we shouldn’t use Assertion with any business logic.

Hint 7:

Try to use containsKey(), containsValue()contains() checks.

package com.crunchify.tutorial;

import java.util.*;

/**
 * @author Crunchify.com
 * 
 */

public class CrunchifyContainsKeyExample {
	public static void main(String args[]) {
		HashMap<Integer, String> crunchifyMap = new HashMap<Integer, String>();

		// populate hash map
		crunchifyMap.put(1, "Crunchify");
		crunchifyMap.put(2, "wordpress");
		crunchifyMap.put(3, "java tutorials");

		// check existence of key 4
		if (crunchifyMap.containsKey(4)) {
			System.out.println("Check if key 2 exists: " + crunchifyMap.get(4));
		} else {
			System.out.println("NPE for value 4 avoided");
		}
	}
}

Hint 8:

As a conclusion it’s always good practice to take care of NPE during development rather debugging in production at runtime. There are number of other tips and tricks available using Spring Framework Annotation, Factory Pattern, Null Object Pattern etc. But I’ll cut this short now.

Will publish new tutorial probably in a week on this one. Stay tuned. Do you want to add anything to this tutorial OR found an issue, please chime in and provide your comments.

Have a suggestion on article? Please chime in and share it as a comment.

The post Have you Noticed java.lang.NullPointerException (NPE)? 8 Best Practices to Avoid runtime NPE in Java appeared first on Crunchify.

Author: App Shah

Crunchify, LLC Logo


Viewing all articles
Browse latest Browse all 1037

Trending Articles