将 String 与 null 进行比较时,为什么会出现 NullPointerException? [英] Why do I get a NullPointerException when comparing a String with null?

查看:27
本文介绍了将 String 与 null 进行比较时,为什么会出现 NullPointerException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码在以下行中出现空指针异常:

My code is breaking on the following line with a nullpointerexception:

 if (stringVariable.equals(null)){

在此语句之前,我声明了 stringVariable 并将其设置为数据库字段.

Previous to this statement, I declare the stringVariable and set it to a database field.

在这个语句中,我试图检测该字段是否具有 null 值,但不幸的是它坏了!

In this statement, I am trying to detect if the field had a null value, but unfortunately it breaks!

有什么想法吗?

推荐答案

使用

stringVariable == null

测试stringVariable是否为null.

equals 方法(以及所有其他方法)要求 stringVariable 不能为 null.

The equals method (and every other method) requires stringVariable to not be null.

这篇关于将 String 与 null 进行比较时,为什么会出现 NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆