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有被其他地方调用多次,
如下图
clipboard.png

阅读 3k
3 个回答

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 之后,直接就抛异常了。

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

a是 null, null 是没有 equals 方法的, 所以 jvm 直接报 NullPointerException了,这和equals方法没有任何关系。

equals 不属于基本的操作方法,比如==,他是Object类的,也就是必须得有一个类对象才可以调用。
你相当于写了 null.equals(); ,IDE的代码提示都会给你提示出错的。
NullPointerException异常,是jre运行时抛出来的,堆栈运行时,需要根据你的对象去堆里面找对象,没找到。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题