In this section, we will learn what the NullPointerException is and how to handle it in Java.
What is Null in JAVA?
In Java, we can create an object and store its reference into a variable of the same type. In a situation like this, the variable has a reference to that object.
But we can also create a variable that is going to store a reference to an object in the future but for now set its value to `null`. The `null` value will initialize the variable, but this value means pointing to nothing! So actually the variable that has such value is considered initialized but is pointing to nothing for now.
Of course, in later time we can assign the reference of an actual object to that variable.
What is NullPointerException in JAVA?
But if we forget to assign a real object to a variable with null value and use the variable in a program anyway, we will get an exception of type the `NullPointerException` class.
Example: throwing NullPointerException in JAVA
public class Simple { public static void main(String[] args) { FileInputStream stream = null; System.out.println(stream.toString()); } }
Output:
Error: Nullpointerexception
In this example, we have a variable named `stream` of type `FileInputStream`. The value stored in this variable currently is `null`. This means the variable is pointing to no object.
After declaring this variable, you can see we’ve called the `toString()` method on this variable. But we know the `stream` variable is referring to no object! So if there’s no object, then there’s no method as well!
This is why we got the `nullpointerexception` as the output of this program.
How to Catch (Handle) NullPointerException in JAVA?
The `nullpointerexception` is an object of type `NullPointerException`. To catch such exception, we can add a catch block that accepts exceptions of type `NullPointerException` and this way we can handle the exception.
Example: handling NullPointerException in JAVA
public class Simple { public static void main(String[] args) { FileInputStream stream = null; try{ System.out.println(stream.toString()); }catch (NullPointerException exception){ System.out.println("The variable is not referring to a real object "); } } }
Output:
The variable is not referring to a real object.
Here, by adding the `catch` block to handle exceptions of type `NullPointerException`, we could handle the `nullpointerexception` correctly and stop the program from crashing.