English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Why can I throw null in Java, and why should I convert it to NullPointerException?

In Java, each type has a default value. When you do not initialize the instance variables of a class, the Java compiler will use these values to initialize them for you. Null is the default value for object types, and you can also manually assign null to an object in a method.

Object obj = null;

However, you cannot use an object with a null value or (if you use a null value instead of an object) an object, as this will throw a NullPointerException.

Example

public class Demo {
   String name = "Krishna";
   int age = 25;
   public static void main(String args[]) {
      Demo obj = null;
      System.out.println(obj.age);
      System.out.println(obj.name);
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:11)

Throw NullPointerException

You can also use the throw keyword to throw a NullPointerException in Java.

Example

public class ExceptionExample {
   public static void main(String[] args) {
      System.out.println("Hello");
      NullPointerException nullPointer = new NullPointerException();
      throw nullPointer;
   }
}

Output Result

Hello
Exception in thread "main" java.lang.NullPointerException
   at MyPackage.ExceptionExample.main(ExceptionExample.java:6

throw a null value

According to the Java documentation, if you try to execute NullPointerException-

  • Call method a (instance) using null object.

  • Access, modify, and print the fields of null value (object).

  • Try to access (print/Use the length of null values in the statement).

  • throw a null value.

  • Access or modify elements with null values/Slot.

means that if a null value is thrown, a NullPointerException will occur, which is not an upcast.

Example

public class Demo {
   public static void main(String args[]) {
      throw null;
   }
}

Runtime Exception

Exception in thread "main" java.lang.NullPointerException
   at july_set3.Demo.main(Demo.java:5)