Null Pointer Exception in Java (original) (raw)

Last Updated : 20 Dec, 2024

A **NullPointerException in Java is a RuntimeException. In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when a program attempts to use an object reference that has the **null value.

**Example:

Java `

// Demonstration of NullPointerException in Java public class Geeks {

public static void main(String[] args) {
  
    // Reference set to null
    String s = null; 
  
    // Throws NullPointerException
    System.out.println(s.length()); 
}

}

`

**Output:

Hangup (SIGHUP) Exception in thread "main" java.lang.NullPointerException at Geeks.main(Geeks.java:10)

**Explanation: In the above example, the string reference "s" is null. When the program tries to call the length() method, it throws a **NullPointerException because there is no actual object.

Reasons for Null Pointer Exception

A **NullPointerException occurs due to below reasons:

**Need of Null Value

The null value serves as a placeholder and it indicates that no value is assigned to a reference variable. Common applications include:

**How to Avoid the NullPointerException?

To avoid the **NullPointerException, we must ensure that all the objects are initialized properly, before we use them. When we declare a reference variable, we must verify that object is not null, before we request a method or a field from the objects.

**1. String Comparison with Literals

A very common case problem involves the comparison between a String variable and a literal. The literal may be a String or an element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal.

**Example:

Java `

// Invoking a method on null // causes NullPointerException import java.io.*;

class Geeks { public static void main (String[] args) {

    // Initializing String variable 
    // with null value
    String s = null;

    // Checking if s.equals null
    try
    {
        // This line of code throws NullPointerException
        // because s is null
        if (s.equals("gfg"))
            System.out.print("Same");
        else 
            System.out.print("Not Same");
    }
    catch(NullPointerException e)
    {
        System.out.print("NullPointerException Caught");
    }
}

}

`

Output

NullPointerException Caught

We can avoid **NullPointerException by calling equals on literal rather than object.

Java `

// Avoiding NullPointerException import java.io.*;

class Geeks { public static void main (String[] args) {

    // Initializing String variable 
    // with null value
    String s = null;

    // Checking if s is null
    // using try catch
    try
    {
        if ("gfg".equals(s))
            System.out.print("Same");
        else 
            System.out.print("Not Same");            
    }
    catch(NullPointerException e)
    {
        System.out.print("Caught NullPointerException");
    }
}

}

`

**Note: Always invoke equals on the literal to avoid calling a method on a null reference.

**2. Checking Method Arguments

Before executing the body of the new method, we should first check its arguments for null values and continue with execution of the method, only when the arguments are properly checked. Otherwise, it will throw an **IllegalArgumentException and notify the calling method that something is wrong with the passed arguments.

**Example:

Java `

// Checking Method Arguments import java.io.*;

class Geeks { public static void main(String[] args) {

    // String s set an empty string 
    // and calling getLength()
    String s = "";
  
    try {
        System.out.println(getLength(s));
    }
    catch (IllegalArgumentException e) {
        System.out.println(
            "IllegalArgumentException caught");
    }

    // String s set to a value
    // and calling getLength()
    s = "GeeksforGeeks";
  
    try {
        System.out.println(getLength(s));
    }
    catch (IllegalArgumentException e) {
        System.out.println(
            "IllegalArgumentException caught");
    }

    // Setting s as null and
    // calling getLength()
    s = null;
  
    try {
        System.out.println(getLength(s));
    }
    catch (IllegalArgumentException e) {
        System.out.println(
            "IllegalArgumentException caught");
    }
}

// Function to return length of string s. It throws
// IllegalArgumentException if s is null.
public static int getLength(String s)
{
    if (s == null)
        throw new IllegalArgumentException(
            "The argument cannot be null");
  
    return s.length();
}

}

`

Output

0 13 IllegalArgumentException caught

**3. Use the Ternary Operator

The ternary operator can be used to avoid NullPointerException. First, the Boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers.

**Example:

Java `

// Ternary operator to avoid NullPointerException import java.io.*;

class Geeks { public static void main(String[] args) {

    // Initializing String variable
    // with null value
    String s = null;
    String m
        = (s == null) ? "" : s.substring(0, 5);

    System.out.println(m);

    // Initializing String variable
    // with null value
    s = "Geeksforgeeks";
    m = (s == null) ? "" : s.substring(0, 5);
    System.out.println(m);
}

}

`

**Explanation: The ternary operator helps check for null and avoid operations on null references.