Java Program to demonstrate NullPointerException
Program
public class NullPointerExceptionDemo
{
public static void main(String args[])
{
try{
String str = null;
System.out.println(str.length());
}
catch(NullPointerException e){
System.out.println("Catching NullPointerException");
}
}
}
This Java program demonstrates how a NullPointerException occurs and how it can be caught and handled using a try-catch block.
-
NullPointerException:- A pointer (or reference) that does not point to any memory location or object is called
null. - Attempting to dereference such a pointer results in a
NullPointerException. - A
NullPointerExceptionoccurs in Java when you attempt to access a method or property on a variable that is set tonull. - In this program, the
String stris explicitly initialized tonull.
- A pointer (or reference) that does not point to any memory location or object is called
-
Code Flow:
- The program tries to calculate the length of the
strstring by calling thelength()method:str.length();. - Since
strisnull, invoking thelength()method results in aNullPointerException.
- The program tries to calculate the length of the
-
Exception Handling:
- The program wraps the code in a
tryblock. - The
tryblock contains the code that might throw an exception. - The
catchblock handles the exception to prevent the program from terminating abnormally. - When the exception occurs, the control is transferred to the
catchblock, where the exception is caught, and a message ("Catching NullPointerException") is displayed. - This prevents the program from crashing due to the unhandled exception.
- The program wraps the code in a
-
Output:
- Instead of terminating abnormally, the program gracefully handles the exception and outputs:
Catching NullPointerException
- Instead of terminating abnormally, the program gracefully handles the exception and outputs:
Output
Catching NullPointerException