Calling a method using null in Java

Object Oriented ProgrammingJava8Java Programming

When a method is invoked on a null reference, it throws NullPointerException but in case of the static method, we can make it possible using cast expression. See the example below −

Example

Live Demo

public class Tester {
   public static void display(){
      System.out.println("display");
   }
   private void print() {
      System.out.println("print");
   }

   public static void main(String[] args) {
      //Scenario 1:
      //Calling a method on null reference
      //causes NullPointerException
      try {
         Tester test = null;           test.print();
      }catch(Exception e) {
         System.out.println(e.getMessage());
      }

      //Scenario 2:
      //Static method can be invoked
      //on a null object by using the casting expression
      ((Tester)null).display();
   }
}

Output

null
display

Notes

  • Scenario 1 demonstrates the code causing NullPointerException.

  • Scenario 2 demonstrates the use of the static method by evaluating a class name on a null object.

raja
Updated on 18-Jun-2020 12:27:06

Advertisements