Java null pointer exception

NullPointerException is a runtime exception and it is thrown when the application tries to use an object reference that has a null value.

Let`s look to the Oracle doc one more time for some definitions of NullPointerException.

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Calling the instance method of a null object.

String str = null;
int length = str.length();

//Output:
//Exception in thread "main" java.lang.NullPointerException

Accessing or modifying the field of a null object.

public class Test500 {
    int salary=150000;

    public static void main(String[] args) {
        Test500 obj = new Test500();
        System.out.println(obj.salary);
    }
 }

//Output:
//150000
public class Test500 {
    int salary=150000;

    public static void main(String[] args) {
        Test500 obj=null;
        System.out.println(obj.salary);
    }
 }

//Output:
//Exception in thread "main" java.lang.NullPointerException

	at vn.com.tca.portal.test.Test500.main(Test500.java:9)

Taking the length of null as if it were an array.

Object [] obj = null;
System.out.println("length:" + obj.length);

//Output:
//Exception in thread "main" java.lang.NullPointerException

Accessing or modifying the slots of null as if it were an array.

Integer[] integerArray = new Integer[3];
integerArray[0]=1;
integerArray[1]=2;

int x = integerArray[0].intValue();
int y = integerArray[1].intValue();
int z = integerArray[2].intValue(); //java.lang.NullPointerException

Throwing null as if it were a Throwable value.

Object obj = null; 
if(obj == null){
     throw new NullPointerException("Hello the obj is null");
}