Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Definition
3.
Possible Scenarios
3.1.
When the Method is Invoked Using a Null Object.
3.1.1.
Example
3.1.2.
Output
3.2.
When a Program Tries to Modify the Null Objects Field
3.2.1.
Example
3.2.2.
Output
3.3.
When We Try to Pass a Null Object in a Method
3.3.1.
Example
3.3.2.
Output
3.4.
When We Try to Operate on a Null Array Object
3.4.1.
Example
3.4.2.
Output
3.5.
When We Try to Synchronise Over a Null Object
3.5.1.
Example
3.5.2.
Output
4.
Avoidance of Null Pointer Exception in Java
4.1.
Scenario1(String Comparison with Literals)
4.1.1.
Example1
4.1.2.
Output1
4.1.3.
Example2
4.1.4.
Output2
4.2.
Scenario2(Checking Arguments of the Method)
4.2.1.
Example
4.2.2.
Output
4.3.
Scenario3(Use of Ternary Operator)
4.3.1.
Example
4.3.2.
Output
5.
Frequently Asked Questions
6.
Conclusion
Last Updated: Mar 27, 2024

Null Pointer Exception in Java

Author Aniket Majhi
1 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Wellcome readers!! I hope you are doing well.

This blog is going to be interesting for you. Nowadays, programming is an essential part of developers. If you want to master any programming field, there are some essential concepts that you can’t avoid. 

This blog will cover such a programming concept, namely the Null Pointer Exception in Java. We will see different aspects where we might face the Null Pointer Exception and how we can avoid such scenarios.

Coding Ninjas also have a four-blog series on Java exceptions and exception handling. Here's a step-by-step guide to help you get the most out of this series.

This may sound daunting at first, but once you've completed the series, exceptions in Java will be a breeze for you.

Must Read, Multithreading in java and Also see, Duck Number in Java

Definition

The null pointer exception in Java is a runtime exception that is thrown when the java program attempts to use the object reference that contains the null value.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Possible Scenarios

The possible scenarios where the null pointer exception can be thrown are as follows:

When the Method is Invoked Using a Null Object.

If we invoke some methods on the null object, Java throws the NullPointerException.

Example

public class Main{

    // returns sum of two numbers
    int sum(int a , int b) {
        return a + b;
    }
    public static void main(String[] args) {
        Main m = null;  // intitialised the object with null value
        // Invoking the method sum on the null object.
        System.out.println(m.sum(10, 20));
    }
}

Output

Practice by yourself on java online compiler.

When a Program Tries to Modify the Null Objects Field

If any program tries to modify the null object field, the NullPointerException is thrown.

Example

public class Main{
    int val = 10;
    public static void main(String[] args) {
        Main m = null;  // intitialised the object with null value
        // It tries to read the data on the null object
        System.out.println(m.val);
    }
}

Output


Also see,  Swap Function in Java

When We Try to Pass a Null Object in a Method

If we try to pass the null object field in a method, the NullPointerException is invoked.

Example

public class Main{

    // the java integer class in given here
    int meth(Integer x){
        return x.intValue();
    }

    public static void main(String[] args) {
        // creating a the object m
        Main m = new Main();

        // trying to invoke the method using the null parameter
        System.out.println(m.meth(null));

    }
}

Output

When We Try to Operate on a Null Array Object

If we try to operate on a null array object, this type of NullPointerException will be thrown.

Example

public class Main{
    // The array arr is set to null
    int arr[] = null;
    public static void main(String[] args) {

        // a object m of type Main is created
        Main m = new Main();

        // trying to print the lenght of the null array
        System.out.println(m.arr.length);

    }
}

Output

When We Try to Synchronise Over a Null Object

When we try to synchronise over a null object, if the object reference for the synchronisation is null, then the NullPointerException is thrown.

Example

public class Main{
    // The static variable val of type String is set to null
    public static String val = null;
    public static void main(String[] args) {

        // Trying to enter to the synchronized block by using val
        synchronized(val) {
            System.out.println("Synchronized");
        }

    }
}

Output

Avoidance of Null Pointer Exception in Java

For Java developers, avoidance of the NullPointerException is an important task. Unlike other programming languages, Java does not provide any method to check for NullPointerException.

To avoid the null pointer exceptions, you need to ensure that every object must be initialised with some value before you use them.

We can consider the following scenarios to deal with the NullPointerException.

Scenario1(String Comparison with Literals)

In this case, we compare a string to a literal.

If the String object is set to null, it throws a NullPointerException, as shown below.

Example1

public class Main{
    public static void main(String[] args) {
        // the string value is initialized to null
        String s = null;
        try{
            // we are checking if the string is equal to "hello" or not
           // if the string is found to be null, then the  NullpointerException will be thrown
            if(s.equals("hello")) {
                System.out.println("The string is \"hello\"");
            }
            else{
                System.out.println("The string is not \"hello\"");
            }
        }
        catch(NullPointerException e){
            System.out.println("NullpointerException");
        }
    }
}

Output1

We can avoid this null pointer exception by invoking the equals() method from the literal.

Let’s see how we can do this in the below example.

Example2

public class Main{
    public static void main(String[] args) {
        // the string value is initialized to null
        String s = null;
        try{
            // we are checking if the string is equal to "hello" or not, by invoking the equals method from the literal "hello"
            if("hello".equals(s)) {
                System.out.println("The string is \"hello\"");
            }
            else{
                System.out.println("The string is not \"hello\"");
            }
        }
     
        catch(NullPointerException e){
            System.out.println("NullpointerException");
        }
    }
}

Output2

Scenario2(Checking Arguments of the Method)

Here, we check the arguments passed to a method for null values. If the arguments are properly checked, then only we execute the body of the function. However, if the arguments are not legitimate, it throws an IllegalArgumentException.

Example

public class Main{
    // method getString() returns the string argument
    public static String getString(String s) {
        // if the string is null it informs the calling method that the argument is illegal.
        if(s == null)
        throw new IllegalArgumentException("The argument is null");
        return s;
    }
    public static void main(String[] args) {

        String s = null;
        try{
            // It throws an IllegalArgumentException
            System.out.println(getString(s));
        }
        catch(IllegalArgumentException e) {
            System.out.println("IllegalArgumentException");
        }

        s = "Hello there!";

        try{
            // It prints the string
            System.out.println(getString(s));
        }
        catch(IllegalArgumentException e) {
            System.out.println("IllegalArgumentException");
        }

    }
}

Output

Scenario3(Use of Ternary Operator)

We can also use the ternary operator to avoid the NullPointerException. Using the ternary operator, we first check the boolean expression, and if it is found to be true, then the first value will be returned. Otherwise, the second value will be returned.

Example

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

        // as s == null, it initializes the variable with the empty string
        String ans = (s == null) ? "" : s;
        System.out.println(ans);

        // as the s != null, it initializes the variable the variable with the whole string.
        s = "hello there";
        ans = (s == null) ? "" : s;
        System.out.println(ans);
    }
}

Output

 Also see, Hashcode Method in Java  

Frequently Asked Questions

  1. What do you mean by the NullPointerException in Java?
    The null pointer exception in Java is a runtime exception that is thrown when the java program attempts to use the object reference that contains the null value.
     
  2. What is an example of the NullPointerException in Java?
    An example of the NullPointerException in Java can be using a null reference to a method.
     
  3. Why do we use null pointers?
    The null pointers are useful when the pointer does not point to a valid memory address.
     
  4. What is a void pointer?
    A void pointer is a kind of pointer where no data type is associated. It can be used to hold the address of any data type and can be typecasted to any type.

Conclusion

In this article, we have extensively discussed the Null Pointer Exception in Java.

We started with the basic introduction of the blog. we coved some of the important key points:- 

  • What is the Null Pointer Exception in Java
  • The cases in which we can get the Null pointer Exception
  • We discussed five cases.
    • The method is invoked with null objects.
    • The program tries to modify the null object.
    • A null object is passed to the method.
    • Operate on the null array object.
    • Synchronise over a null object.
  • Avoidance of the Null Pointer Exception.
  • We discussed three different scenarios, string comparisonchecking arguments and use of the ternary operators.

We hope that this blog has helped you enhance your knowledge regarding Null Pointer Exception in Java and if you would like to learn more, check out our articles on Converting Java String to IntChar to Int in Java. Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more.!

Happy Reading!

Previous article
Final vs Finally vs Finalize
Next article
User-defined Custom Exception
Live masterclass