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
NullPointerException
occurs in Java when you attempt to access a method or property on a variable that is set tonull
. - In this program, the
String str
is 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
str
string by calling thelength()
method:str.length();
. - Since
str
isnull
, invoking thelength()
method results in aNullPointerException
.
- The program tries to calculate the length of the
-
Exception Handling:
- The program wraps the code in a
try
block. - The
try
block contains the code that might throw an exception. - The
catch
block handles the exception to prevent the program from terminating abnormally. - When the exception occurs, the control is transferred to the
catch
block, 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