Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

NullPointerException in Java

An exception in Java is an abnormal event that occurs during the execution of a program, disrupting its normal flow. It signals that something unexpected has happened that requires special handling. Nullpointerexception in Java is one of the most common exceptions and can occur in many different scenarios, which we will discuss later on in this article, It’s important to catch and handle the nullpointerexception to prevent your program from crashing and provide a better user experience. The exception message usually provides information about the location of the error and can be useful for debugging purposes.

Java Nullpointer Exception

A NullPointerException in Java is a runtime error that occurs when you try to access an object reference that is null. In other words, when you try to use an object reference that does not point to any instance of an object, the JVM throws a NullPointerException. This is because in Java, accessing any property or calling any method on a null object reference is illegal.

The error message of a NullPointerException typically contains the name of the class and method that caused the error, along with the line number where the error occurred.

To prevent a NullPointerException, it is important to check for null values before trying to access an object. This can be done using an if statement or a null-check operator (?.). Additionally, it is a good practice to initialize object references as soon as they are declared, so that they are not null when they are later used.

In summary, a NullPointerException is a common error in Java that occurs when you try to access an object reference that is null. To avoid this error, it is important to check for null values before accessing an object and to initialize object references as soon as they are declared.

Refer to the below code to understand NullpointerException in java more clearly

import java.util.*;
import java.lang.*;
import java.io.*;

class PrepBytes
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // Setting null value to the To_Name object
        Object To_Name = null;

        // Using an object with a null value
        System.out.println(To_Name.toString()); 
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at PrepBytes.main(Main.java:13)

In the above code, we initialized the null value to an object To_Name. On the To_Name object, we performed the toString() operation, because the value of To_Name is null it throws the nullpointerexception as shown in the output.

Various Scenarios For Nullpointer Exception in Java

NullpointerException in Java can occur in several scenarios, some of the most common ones are:

Accessing an object property or method on a null reference:
If you try to access a property or call a method on an object reference that is null, you will get a NullpointerException.

Here’s an example of the above scenario:

import java.util.*;
import java.lang.*;
import java.io.*;

class Person {
  int age;

  public void setAge(int age) {
    this.age = age;
  }
}

public class Main {
  public static void main(String[] args) {
    Person PrepBuddy = null;
    // Accessing a property on a null reference
    System.out.println(PrepBuddy.age); // throws NullPointerException
    // Calling a method on a null reference
    PrepBuddy.setAge(30); // throws NullPointerException
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:17)

In this example, PrepBuddy is a null reference, so trying to access its age property or call its setAge method will result in a NullPointerException. To avoid this, you need to check for a null reference before accessing it.

Calling a method on a null reference passed as an argument: If you pass a null reference as an argument to a method, and that method tries to access a property or call a method on the null reference, you will get a NullPointerException.

Here’s an example of the above scenario:

import java.util.*;
import java.lang.*;
import java.io.*;

class Person {
  int age;
  public void setAge(int age) {
    this.age = age;
  }
}

public class Main {
  public static void updateAge(Person person, int age) {
    person.setAge(age);
  }	
  public static void main(String[] args) {
    Person person = null;
    // Calling a method and passing a null reference as an argument
    updateAge(person, 30); // throws NullPointerException
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.updateAge(Main.java:14)
at Main.main(Main.java:19)

Accessing an element of a null array: If you try to access an element of a null array, you will get a NullPointerException.

Here’s an example of the above scenario:

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
  public static void main(String[] args) {
    int[] numbers = null;

    // Accessing the index of a null array will give NullPointerException
    System.out.println(numbers[1]); // throws NullPointerException
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:10)

Use of null return values: If a method is expected to return an object reference, but it returns null, you will get a NullPointerException if you try to access a property or call a method on the null return value.

Here’s an example of the above scenario:

import java.util.*;
import java.lang.*;
import java.io.*;

class Person {
  private String name;
  public String getName() {
    return name;
  }
}

public class Main {
  public static void main(String[] args) {
    Person PrepBuddy = new Person();

    // Getting the name from a person object
    String name = PrepBuddy.getName();

    // Using the name
    System.out.println(name.toUpperCase()); // throws NullPointerException
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:20)

In this example, the getName method is called and returns null, so trying to call the toUpperCase method on the name reference will result in a NullPointerException. To avoid this, you need to check for a null value before using it.

Use of null object references returned by constructor: If you try to access a property or call a method on an object reference returned by a constructor, but the constructor returns null, you will get a NullPointerException.

import java.util.*;
import java.lang.*;
import java.io.*;

class Person {
  private String name;

  public Person() {
    name = null;
  }

  public String getName() {
    return name;
  }
}

public class Main {
  public static void main(String[] args) {
    // Creating a person object
    Person PrepBuddy = new Person();

    // Using the person object
    System.out.println(PrepBuddy.getName().toUpperCase()); // throws NullPointerException
  }
}

Output:

Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:23)

In conclusion, these are some of the common scenarios where a NullPointerException can occur in Java. To avoid this error, it is important to properly initialize object references, check for null values before accessing an object, and to handle any null return values appropriately.

How to handle Nullpointer Exception in Java

There are several ways to handle NullPointerException in Java:

Check for null values before using them: Before accessing an object property, method, or array element, you should check if the reference is null. This can be done with an if statement or a ternary operator.

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
  public static void main(String[] args) {
   String PrepBuddy = null;
    if (PrepBuddy != null) {
    System.out.println(PrepBuddy.toUpperCase());
    } else {
    System.out.println("PrepBuddy is null");
    }
  }
}

Output:

PrepBuddy is null

Use a try-catch block: You can use a try-catch block to handle the NullPointerException and provide a custom error message or recovery logic.

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
  public static void main(String[] args) {
        String PrepBytes = null;
        try {
            System.out.println(PrepBytes.toUpperCase());
        } 
        catch (NullPointerException e) {
            System.out.println("PrepBytes is null");
        }
    }
}

Output:

PrepBytes is null

Use of Ternary Operator: It is also reasonable to use the ternary operator to check whether or not the given argument is null.

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main {
  public static void main(String[] args) {
        String myPrepBytes = null;
        String message = (myPrepBytes == null) ? "Can not perform operation because myPrepBytes is null" : myPrepBytes.toUpperCase();
        System.out.println(message);
    }
}

Output:

Can not perform operation because myPrepBytes is null

Summary

  • A Nullpointerexception is a runtime exception in Java.
  • When the program uses a reference to an object that has been set to null, a null pointer exception occurs.
  • There are multiple scenarios when the Nullpointerexception occurs in java, for example when we Access an object property or method on a null reference or when we try to access an element of a null array.
  • We can address Nullpointerexceptions by making changes to our applications, such as invoking methods directly using literals instead of null objects, or by using conditional checks to avoid invalid object invocation.

Leave a Reply

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