Why can I throw null in Java and why does it upcast to a NullPointerException?


In Java there is default value for every type, when you don’t initialize the instance variables of a class Java compiler initializes them on your be-half with these values. Null is the default value of the object type, you can also manually assign null to objects in a method.

Object obj = null;

But, you cannot use an object with null value or (a null value instead of an object) if you do so, a NullPointerException will be thrown.

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);
   }
}

Run time exception

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

Throwing NullPointerException

You can also throw a NullPointerException in Java using the throw keyword.

Example

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

Output

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

Throwing null value

According to Java documentation a NullPointerException occurs if you try to −

  • Call the a method (instance) using null object.
  • Access, modify, print, field of a null value (object).
  • Trying to access (print/use in statements) the length of null value.
  • Throw a null value.
  • Accessing or modifying elements/slots of a null value.

Means if you throw a null value a null pointer exception occurs it is not up casting.

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)

Updated on: 02-Jul-2020

946 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements