java null equals NullPointerException

问题描述

String a = null;
boolean flag3 = a.equals("a");

运行后会报错

Exception in thread "main" java.lang.NullPointerException

问题出现的环境背景及自己尝试过哪些方法

在equals源码中,只看到

if (this == anObject) {
    return true;
}
if (anObject instanceof String) {
    String anotherString = (String)anObject;
    int n = value.length;
    if (n == anotherString.value.length) {
        char v1[] = value;
        char v2[] = anotherString.value;
        int i = 0;
        while (n-- != 0) {
            if (v1[i] != v2[i])
                return false;
            i++;
        }
        return true;
    }
}
return false;

疑问1:
在equals中,并没有抛出异常,那么这个异常是在哪里抛出的呢?这个可能涉及到底层jvm相关的知识了,但是我目前完全不知道该怎么去了解这块。

问题2:
在dubugger过程中,打断点运行时候发现,在运行到当前语句之前,equals有被其他地方调用多次,
如下图

最佳答案

java SE 13 specification

15.11. Field Access Expressions

FieldAccess:
    Primary . Identifier
    super . Identifier
    TypeName . super . Identifier

15.11.1. Field Access Using a Primary
At run time, the result of the field access expression is computed as follows: (assuming that the program is correct with respect to definite assignment analysis, that is, every blank final variable is definitely assigned before access)
......

  • If the field is not static:

    • ......
    • If the value of the Primary is null, then a NullPointerException is thrown.

这里进不了 equals 函数。a 求值为 null 之后,直接就抛异常了。