What is NullPointerException in Java?

[1809 views]


NullPointerException error in Java

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:
  • Invoking or Calling a method from a null object.
  • Taking the length of null, as if it were an array.
  • Accessing or modifying a null object's field or variable.
  • Throwing null explicitly, as if it were a Throwable value.
  • Trying to synchronize over a null object.

Why there is a need for the null value?

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.

        


Need Programming or any Technical Related Books, Courses or Help Chat with us

Myntra [CPS] IN

Comments



Sponsored Advertisement


Udemy WW



Norton [CPS] WW

Search
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online


Search Tags