Java error java.lang.nullpointerexception

NullPointerException is the exception that occurred when a programmer perform an operation on a object or calling a method on the object i.e null. This exception is thrown by JVM.

Java error java.lang.nullpointerexception

Java error java.lang.nullpointerexception

     

NullPointerException  is the exception that occurred when a programmer perform an operation on a object  or calling a method on the object i.e null. This exception is thrown by JVM.We should not handle that exception by try and catch block  The only way to resolve Null Pointer Exception is to avoid performing the operation on an object or method of the object i.e is null.

Understand with Example

In this Tutorial we want to describe you a code that help you in understanding a Java Null pointer Exception. For this we have a class javaerrornullpointerexception.Inside this class we have a main method that declare a String array to hold the dimensional size of 5.

string.charAt( )-This method return you the position of the character specified by the  index of the parameter.

On the execution of the code ,the program code show us an error i.e java.lang .Null Pointer Exception because  we have not initialized the value of string array.

javaerrornullpointerexception.java


public class javaerrornullpointerexception {

  public static void main(String args[]) {
  String string[] new String[5];  
  System.out.println(string[1].charAt(1));

  }
}

Output

Compiling source file to /home/girish/NetBeansProjects/errors/build/classes
compile-single:
run-single:
Exception in thread "main" java.lang.NullPointerException
  at javaerrornullpointerexception.main(javaerrornullpointerexception.java:8)
Java Result: 1
BUILD SUCCESSFUL (total time: seconds)

To resolve this error you have to initialise array as shown string[1]="dgdsf"

Download code