NULL Pointer Exception in Java
Scenario :
- In java NullPointerException is a RuntimeException.
- Generally, in java a special null value can be assigned to an object reference.
- NullPointerException throws an exception when an application attempts to use an object reference that has null value.
These exceptions include
- By Calling an instance method on the object referred by a null reference.
- Accessing or modifying an instance field of the object referred by a null reference.
- If the reference type is an array type, taking the length of a null reference.
- If the reference type is an array type, accessing or modifying the slots of a null reference.
- If the reference type is a subtype of Throwable, throwing a null reference.
Object Wikitechy_obj = null;
Wikitechy_obj.toString(); // This statement will throw a NullPointerException
Reason:
In java a NullPointerException is a Runtime Exception and the Javac compiler does not force to use a try-catch block to handle it appropriately.
Fix1:
For example, observe the following
Here in this example code a null pointer exception occur when the dereference of the variable that’s pointing as null.
String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
Fix2:
- In Java everything will be working in the form of class.
- If we want to use any object, they have two phases
1. Declare
2. Initialization
Example:
Similarly, in an array:
- Declaration: Item i[]=new Item[5];
- Initialization: i[0]=new Item();
If we not initialize the object (or) variable inside the Initialization section, then the NullpointerException is occur.
Fixes are applicable to the following versions of Java:
- NullPointerException (Java Platform SE 7 )
- NullPointerException issues (Java)
- Java 8 Optional - Avoid Null and NullPointerException
Applies to:
Related Error Tags:
- nullpointerexception in java example
- how to handle nullpointerexception in java
- how to solve nullpointerexception in java
- nullpointerexception in java example program
- numberformatexception in java
- nullpointerexception in java how to fix
- nullpointerexception in java array