Home » Java programming language

How to avoid NullPointerException in Java?

Avoiding NullPointerException in Java: Here, we are going to learn how to avoid NullPointerException in java?
Submitted by Preeti Jain, on July 06, 2019

Avoiding NullPointerException

  • NullPointerException is when we assign a null value to an object reference.
  • It may raise NullPointerException when a program attempts to use an object reference that holds null value.
  • We will study how to avoid NullPointerException. There are various ways to avoid this exception:

1) To avoid NullPointerException we should remember one thing i.e. we must initialize all object references with specified values before using.

public void display(String str) {
    if (str.equals("Java")) {
        System.out.println("Java");
    }
}

In the above case, NullPointerException can occur if the parameter str is being passed as a null value. The same method can be written as below to avoid NullPointerException.

public void display(String str) {
    if ("Java".equals(str)) {
        System.out.println("Java");
    }
}

2) We should add a null check for parameter and throw IllegalArgumentException if required.

public int CountClassObjects(Object[] count) {

    if (count == null) throw new IllegalArgumentException("No class objects is refernced");

    return count;
}

3) We should use String.valueOf() instead of toString() method. Object obj = null;

//prints null
System.out.println(String.valueOf(obj));

//This statement will throw java.lang.NullPointerException
System.out.println(obj.toString());

Example: Raising NullPointerException

public class NullPointerExceptionClass {
    public static void main(String[] args) {
        String str = null;
        System.out.println("Display String length is " + str.length());
        System.out.println("The String representation is " + str.toString());
    }
}

Output

D:\Programs>javac NullPointerExceptionClass.java
D:\Programs>java NullPointerExceptionClass

Exception in thread "main" java.lang.NullPointerException
        at Java7.main(Java7.java:4)

Example: UnRaising NullPointerException

public class UnRaisingNullPointerClass {
    public static void main(String[] args) {
        String str = null;
        System.out.println("Display String is " + str);
        System.out.println("Display String value is " + str.valueOf(str));
    }
}

Output

D:\Programs>javac UnRaisingNullPointerClass.java
D:\Programs>java UnRaisingNullPointerClass

Display String is null
Display String value is null


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.