javacodex.com
Java Examples
Java Examples
memu home questions

Example Of A NullPointerException

This java example shows how to cause a NullPointerException.

Source: (NullPointerExample.java)

public class NullPointerExample {
   public static void main(String[] args) {
      String str = "This is a string";
      System.out.println(str);
      System.out.println(str.length());
 
      str = null;
      System.out.println(str);
 
      // Should trigger NullPointerException
      System.out.println(str.length());
   }
}
 

Output:

$ java NullPointerExample 
This is a string
16
null
Exception in thread "main" java.lang.NullPointerException
      at NullPointerExample.main(NullPointerExample.java:11)

Contact: javacodex@yahoo.com