laitimes

Learn Java from scratch what to do with the famous NullPointerException

author:IT technology control

I. Introduction

Which exception in Java is the most famous, then I have to say NullPointerException!

NullPointerException, abbreviated as NPE. This can be said to be an exception that everyone knows and knows about Java programmers! Null pointer exceptions are often caused by the programmer not considering that the value of a variable or object may be null, or failing to judge a null value. So when we try to access or operate on a null object, we throw a NullPointerException exception.

NullPointerException exceptions are thrown at runtime, and if not handled, they will cause the program to break or crash, so we should pay special attention to avoid null pointer exceptions when writing Java programs.

II. Causes

There is only one fundamental reason why the NullPointerException null pointer exception occurs, that is, "the object is empty", which is the same problem as many single dogs, hiahia. That is, when an object is null, you have to call the object's methods or fields, and the JVM will generate a NullPointerException, for example:

java复制代码public static void main(String[] args) {
    String s = null;
    System.out.println(s.toUpperCase());
}
           

When the above code runs, it will definitely produce a null pointer exception because the object "s" is null. That is, we did not assign a value to the object initialization, it is just an empty shell, you have to use it, and then something will happen.

Typical cases

Although we now know the cause of the null pointer exception, in order to avoid this common exception, Yi Ge still wants to list a few typical situations that will throw a null pointer exception.

3.1 Call methods or access properties on empty objects

When an object is null, it doesn't have any properties and methods, and if we call methods or access properties on this empty object, we throw a null pointer exception. For example:

java复制代码String str = null;
int length = str.length();  // 会抛出空指针异常
           

3.2 Array elements are null

In Java, elements in an array may also be null. If we call a method or access a property on a null array element, we likewise throw a null pointer exception. For example:

java复制代码String[] strs = new String[3];
strs[0] = "Hello";
strs[1] = null;
int length = strs[1].length();  // 会抛出空指针异常
           

3.3 The parameter is null

When calling a method, if the parameter is null, but the parameter is required inside the method, a null pointer exception will also be thrown. For example:

java复制代码public void printString(String str) {
    System.out.println(str.length());
}

String str = null;
printString(str);  // 会抛出空指针异常
           

Fourth, solutions

In order to avoid the occurrence of null pointer exceptions, we need to strengthen the judgment of variables and objects, and if we find that their values are null, we need to deal with them early, such as setting default values or throwing exceptions. We need to know that NullPointerException is actually a code logic error, encounter NullPointerException, follow the principle of "early exposure, early fix", do not use catch statements to hide this coding error! For example, the following code will not work:

java复制代码// 错误示例: 捕获NullPointerException
try {
    transferMoney(from, to, amount);
} catch (NullPointerException e) {
    //不要去捕获空指针异常!
}
           

Next, Brother Yi will list a few commonly used methods to avoid null pointer exceptions.

4.1 Terms of Use judgment语句

By determining whether the variable is null, you can avoid the occurrence of null pointer exceptions. For example:

java复制代码String str = null;
if (str != null) {
    int length = str.length();
}
           

4.2 Using Object Initialization Statements

Before we use an object, make sure to initialize it so that the object is not null. For example:

java复制代码String str = "";
int length = str.length();
           

When we write business logic, we use an empty string "" to mean unfilled instead of the default null, "" empty string is much safer than null, which avoids many NullPointerExceptions.

4.3 Use the Objects.requireNonNull() method

The Objects.requireNonNull() method can tell if the parameter is null, and if it is, throws a NullPointerException exception. For example:

java复制代码String str = null;
Objects.requireNonNull(str, "str不能为空");  // 会抛出NullPointerException异常
           

4.4 Returns an empty array

If we use arrays and there is no data in an array, we can return an array with empty elements, but do not return null, for example:

java复制代码public String[] getData(String item) {
    if (getItem(item) == 0) {
        // 返回空数组而不是null:
        return new String[0];
    }
    ...
}
           

This eliminates the need for callers to check whether the result is null.

4.5 Use of Optional

Optional is a very useful class introduced in Java 8 to solve the null value problem. It is a container object that may contain non-null or null values, the main purpose is to reduce null pointer exceptions in code, and when the caller must determine whether an object is null, you can consider using Optional. Next, Brother Yi will write a simple Optional case for everyone.

java复制代码import java.io.IOException;
import java.util.Optional;

/**
 * @author 一一哥Sun 
 */
public class Demo13 {
    public static void main(String[] args) throws IOException {
        String str="一一哥";
        //创建一个包含非空值的Optional对象。如果传入的值为null,则会抛出NullPointerException异常。
        Optional<String> optional = Optional.of(str);
        if(optional.isPresent()) {
            String value = optional.get();
            System.out.println("value="+value);
        }else {
            System.out.println("字符串为空");
        }
        //ofNullable方法
        String name = null;
        //Optional.ofNullable静态工厂方法,创建一个包含指定值的Optional对象,如果传入的值为null,则返回一个空的Optional对象
        Optional<String> optionalName = Optional.ofNullable(name);
        String orElse = optionalName.orElse("Unknown");
        System.out.println("值="+orElse);
    }
}
           

We can use the Optional.of static factory method to create an Optional object with a non-null value that throws a NullPointerException exception if the value passed in is null. And you can use the isPresent() method to determine whether an Optional object contains non-null values. Returns true if it contains a non-null value, false otherwise.

You can also use the Optional.ofNullable static factory method to create an Optional object that contains the specified value, and returns an empty Optional object if the value passed in is null. Then use the orElse() method to get the value contained in the Optional object, and if the Optional object is empty, return the specified default value.

There are still many more ways to use Optional, and in the future, Brother One will release a special series of new Java features, so I won't go into detail here, so stay tuned.

4.6 Locate null pointer exceptions

When we write code that really generates a null pointer exception, what should we do? Brother Yi told you earlier that the root cause of the null pointer exception is because "the object is empty", so the solution is to find the empty object first, and then assign a value to the object, as long as the object is not empty, the null pointer exception is solved. It doesn't sound difficult, but when really developing, sometimes inexperienced programmers may not be able to find which object is empty for a while. Because there are so many objects in our project! For example, the following code:

java复制代码a.b.c.method()
           

A, B, and C here are all objects, if this line of code generates a null pointer, which object do you say is empty? It may be that a is empty, it may be b, or it may be c, usually we have to judge one object by one, such as by printing a log to judge:

java复制代码System.out.println(a);
System.out.println(a.b);
System.out.println(a.b.c);
           

But writing code like this is verbose and inefficient! To improve this problem, a new API was introduced in JDK 14 that allows the JVM to give us detailed information directly about which null object it is. In JDK 14, if the above code generates a null pointer exception, a prompt appears like this: ... because ".... a.b" is null.... This means that the b object is null. But this feature is turned off by default, we need to add a -XX:+ShowCodeDetailsInExceptionMessages parameter to the JVM to enable it, as follows:

java复制代码java -XX:+ShowCodeDetailsInExceptionMessages Main.java
           

The above are several common methods listed by Yi Ge to avoid and check null pointer exceptions, I hope you can master.

In short, when we write Java programs, we should pay special attention to avoid the occurrence of null pointer exceptions, strengthen the judgment of variables and objects, and develop good coding habits, which can greatly reduce the generation of NullPointerException. If the value is found to be null, it needs to be handled early to avoid program interruption or crash.

------------------------------ feature film is over, come to the root of the smoke after the fact----------------------------

V. Conclusion

In this way, Brother Yi analyzed the particularly common exception of the null pointer to everyone separately, and I hope that you can know how to solve this exception in the future. Today's highlights are as follows:

The root cause of NullPointerException is that the object is empty; Null pointer exceptions should be exposed and fixed as soon as possible, and do not use catch to catch them; Java 14's enhanced exceptions can be enabled to locate where null pointer exceptions originate.