Chapter 01 What is a null pointer exception?

Null pointer appears in many languages, Java hollow pointer exception is Java. Lang. NullPointException, we all know that the object is stored in the memory of the null pointer exception, is empty, empty is memory address pointer is refers to the object is point to other objects or reference, The exception object (reference data type) is blown when referenced and is null if not initialized. This is the root cause of null-pointer exceptions

Section 01 common null pointer exception

Create a Maven project. Add Package com.citi.npe create NpeApplication and add main method

public class NpeApplication {

    public static void main(String[] args) {}}Copy the code

Create entity package and add User entity class

public class User {

    public String name;
    public String[] books;

    public void say(a){
        System.out.println("This is say method");
    }

    public String readBook(a){
        System.out.println("This is read book method");
        return null; }}Copy the code

Symptom 1: Properties of an empty object are accessed

public static void callNullObjectAttribute(a){
    User user = null;
    System.out.println(user.name);
}
Copy the code

When callNullObjectAttribute() is called in the main method, the console prints a null-pointer exception

Symptom 2: An instance method of an empty object is called

public static void callNullObjectMethod(a){
    User user = null;
    user.say();
}
Copy the code

When callNullObjectMethod() is called in the main method, the console prints a null-pointer exception

Phenomenon 3: When an array is an empty object, take its length

public static void getLenFromNullArray(a){
    User user = null;
    System.out.println(user.books.length);
}
Copy the code

Call getLenFromNullArray() in the main method, and the console prints a null pointer exception

Symptom 4: An empty runtime exception is thrown

Add the exception package, add CustException custom RuntimeException class, and inherit RuntimeException

public static void throwNullException(a){
    CustException custException = null;
    throw custException;
}
Copy the code

Call throwNullException() in the main method to throw a null-pointer exception

Symptom 5: Operating on an empty object returned by a method

public static void opNullObjReturnFromMethod(a){
    User user = null;
    System.out.println(user.readBook().contains("book"));
}
Copy the code

The main method invokes the opNullObjReturnFromMethod (), the console print out null pointer exception

How do I avoid null-pointer exceptions

  • An object must be initialized or verified before being used
  • Do not set the function return value to NULL
  • Be sure to judge the object you receive

Section 02 assignment auto unboxing null pointer exception

A null pointer exception occurs when the assignment is automatically unpacked

Null pointer raised by automatic unpacking

  • Variable assignment automatically unboxing raises a null pointer
  • Method to pass parameters automatically unboxing raises a null pointer

Create an UnboxingNpeApplication under the NPE package

public class UnboxingNpeApplication {

    public static void main(String[] args) {}}Copy the code

Null pointer for automatic unboxing during variable assignment is abnormal

public static void assignValueByUnboxing(a){
    Integer i = null;
    int i_01 = i;
    System.out.println(i_01);
}
Copy the code

The main method calls assignValueByUnboxing(), and the console prints a null pointer error message

Method The empty pointer is abnormal when the parameter is automatically unpacked

public static void passArguByUnboxing(a){
    Integer x = null;
    Integer y = null;
    add(x,y);
}

public static int add(int x, int y){
    return x + y;
}
Copy the code

The main method calls passArguByUnboxing(), and the console prints the following error message

Suggestions for avoiding null pointer exceptions

  • Base and reference data types, with priority given to base data types
  • Judgment validation for uncertain wrapper types
  • Zero is assigned starting for a null wrapper

Section 03 – The collection has a null pointer

Add CollectionNpeApplication and add main method

Strings compare space-time Pointers using the equals() method

public static boolean isEqualStringAndNull(String x, String y){
    return x.equals(y);
}
Copy the code

Called in the main method

public static void main(String[] args) {
    // constant.equals(variable)
    boolean isEqual = isEqualStringAndNull("abc".null);
    System.out.println(""abc"Compare with NULL :" + isEqual);
    boolean isEqual1 = isEqualStringAndNull(null."abc");
    System.out.println("Null and"abc"More." + isEqual1);
}
Copy the code

The console prints null. Equals (” ABC “). The string is compared to null using equals(), and the variable is placed in the equals() argument

The empty object space-time pointer in the operation object array adds a method to the test class

public static void emptyObjectArray(a){
    User[] userList = new User[5];
    for (int i = 1; i <= userList.length; i++) {
        // If userList[I] is null, it cannot pass. Attribute
        userList[i].name = "stark no."+ i; }}Copy the code

Execute the static method, userList[I] is null, and pass. Property also returns a null pointer error

List,ArrayList executes addAll(null) spacetime pointer Check out the source code for the addAll() method of ArrayList

The toArray() method is used, and since the argument itself is null, an error is reported