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")) {

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)) {

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

//This statement will throw java.lang.NullPointerException

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());


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));


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

Display String is null
Display String value is null

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.