[3643 views]
NullPointerException is defined as a RuntimeException in Java. In Java, a special null value can be assigned to an object reference, meaning that the object has not yet been assigned any value or the object doesn't have any value. NullPointerException is thrown by Java Compiler at runtime when program attempts to use an object reference which has null value.
NullPointerException is thrown while:Null is a very special value used in Java language. It is mainly used to indicate that no value has been assigned to the reference variable yet. One of the application of null value is in implementing data structures like tree and linked list. Other applications include Null Object Design pattern and Singleton Design pattern. The Singleton Design pattern ensures that only one instance or only one object of a class is created and also, it aims for providing a global point of access to the object.
To avoid NullPointerException, what you must do is to verify that object is not null, before you request a method or a field from that object. You must also ensure that all the objects you use are properly initialized.
You can also handle NullPointerException by using try and catch block. But it's RuntimeException so we don't need to catch it in our program.