What is Null Pointer Exception in Java

Null Pointer Exception in Java

A Null Pointer Exception in java is a type of runtime exception thrown when a Java program tries to use an object reference that contains a null value. A null pointer exception can be thrown in the following scenarios:

  • Calling an instance method of a null object.
  • Accessing or modifying a field of a null object.
  • Gets the length of null as if it were an array.
  • Access or modify null slots as if they were arrays.
  • Throw null as if it were a Throwable value.

Null Pointer Exception in Java Example

Here is an example of a Null Pointer Exception thrown when the length() method of a null String object is called.

In this example, the printLength() method calls the String’s length() method without performing a null check before calling the method. Since the string value passed from the main() method is null, running the above code will result in a Null Pointer Exception.

Null Pointer Exception in Java Example

Output:

Other Popular Articles

How To Create Custom Exception in Java

Leave a Comment