Null Pointer Dereference

Null Pointer Dereference

Overview

Null pointer dereference happens when code uses a value after it may be null.

Impact

It can cause application crashes and may lead to denial of service.

Countermeasures

Check return values, fail fast on invalid state, use Optional-style APIs where suitable, and keep null checks close to use sites.

Examples

public Object returnNull() {
    return null;
}

public void testNull() {
    String str = returnNull().toString();
}
public void getInputFromFile() {
    try {
    BufferedReader br = new BufferedReader(new FileReader("input.dat"));
    String str = br.readLine();
    str.toUpperCase();
   ...
}
public class ForwardNullEx {
    public void test() {
        String uppercased = toUpperCase(null);
    }

    public String toUpperCase(String arg) {
       arg.toUpperCase();
    }
}
public class UncheckedNullEx {
    public void test(String x) {
        String str = "";
        System.out.println(str);
        if(x != null) {
            str = x.toUpperCase();
        }
        x.toString();
    }
}