NullPointerException In Java
NullPointerException occurs when you perform an operation on a object or calling a method on the object. The only way to solve Null Pointer Exception is to avoid executing operation on a object or calling a method on the object.
Example
Given below example will give you a clear idea :
package simpleCoreJava; public class JavaNullpointerexception { public static void main(String args[]) { String string[] = new String[2]; System.out.println(string[1].charAt(1)); } }
Code Description
In the above class we have declared a String array which has size 2. But we haven't initialize the array therefore at position 1 there is nothing. So When we call charAt() function, the above code throw NullPointerException.
Output
Exception in thread "main" java.lang.NullPointerException at simpleCoreJava.JavaNullpointerexception.main(JavaNullpointerexception.java:8) |
Correction of the above code
You can Correct the above code as follows :
package simpleCoreJava; public class JavaNullpointerexception { public static void main(String args[]) { String string[] = new String[3]; string[0] = "ankit"; string[1] = "ankit"; string[2] = "ankit"; System.out.println(string[1].charAt(1)); } }
The Output of the above code will be :
n |