Is there a scenario where autoboxing and unboxing could cause a NullPointerException?

Yes, a NullPointerException can occur during unboxing when a wrapper object contains a null value and Java attempts to convert it into its corresponding primitive type. Since primitive types cannot hold null values, the JVM throws a NullPointerException.

Key Points: • Unboxing converts a wrapper object into a primitive data type automatically. • If the wrapper object is null, Java cannot extract a primitive value from it. • This results in a NullPointerException at runtime. • The issue commonly occurs with wrapper classes such as Integer, Double, Boolean, and Long. • Always perform a null check before unboxing wrapper objects.

Example: An Integer variable can store null, but when Java tries to convert that null value into an int, a NullPointerException is thrown.

Code Example:

public class Demo {

    public static void main(String[] args) {

        Integer number = null;

int value = number; // Causes NullPointerException

        System.out.println(value);
    }
}

Interview Tip: A concise interview answer is:

"Yes, a NullPointerException can occur during unboxing if a wrapper object contains null. Since primitive types cannot store null values, Java throws a NullPointerException when it attempts to convert a null wrapper object into a primitive type."