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.

  1. 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 to null.
    • In this program, the String str is explicitly initialized to null.
  2. Code Flow:

    • The program tries to calculate the length of the str string by calling the length() method: str.length();.
    • Since str is null, invoking the length() method results in a NullPointerException.
  3. 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.
  4. Output:

    • Instead of terminating abnormally, the program gracefully handles the exception and outputs:
      Catching NullPointerException
      

Output

Catching NullPointerException