
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calling a Method Using Null in Java
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
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.
Advertisements