[英]Why do I get a NullPointerException when comparing a String with null?
My code is breaking on the following line with a nullpointerexception: 我的代码使用nullpointerexception破坏了以下行:
if (stringVariable.equals(null)){
Previous to this statement, I declare the stringVariable and set it to a database field. 在此声明之前,我声明了stringVariable并将其设置为数据库字段。
In this statement, I am trying to detect if the field had a null
value, but unfortunately it breaks! 在这个声明中,我试图检测该字段是否具有
null
值,但不幸的是它会中断!
Any thoughts? 有什么想法吗?
Use 使用
stringVariable == null
To test whether stringVariable
is null
. 测试
stringVariable
是否为null
。
The equals
method (and every other method) requires stringVariable
to not be null
. equals
方法(以及所有其他方法)要求stringVariable
不为null
。
if stringvariable
is already null, it doesn't exist as a String
object anymore, so it won't even have a .equals
method! 如果
stringvariable
已经为null,则它不再作为String
对象存在,因此它甚至不会有.equals
方法! So in the event when stringvariable
is null, what you are really doing is null.equals(null)
, at which point you'll get the NullPointerException
because null
doesn't have a .equals()
method. 所以在
stringvariable
为 null的情况下,你真正做的是null.equals(null)
,此时你将得到NullPointerException
因为null
没有.equals()
方法。
It is never wise to call a method, be it equals() or otherwise,on a variable which may be null. 在一个可能为null的变量上调用一个方法,无论是equals()还是其他方法都是不明智的。 That is why one usually does something like:
这就是为什么人们通常做的事情:
if ( var != null && var.method(something) ) {
// var.method() was true
} else {
// var is null or var.method is false
}
In your special case it would be sufficient to do 在你的特殊情况下,这样就足够了
if (stringVariable == null) {
}
when working with Strings it can pay to check out Apache Commons StringUtils . 使用Strings时,可以付费查看Apache Commons StringUtils 。
It always pays to check out the apache commons libraries as they have lots of optimized utilities (for Strings, Collections, Dates and such) which tend to be better than home-written ones. 检查apache commons库总是值得的,因为它们有很多优化的实用程序(对于字符串,集合,日期等),这些实用程序往往比自制的更好。
The equals() method does not work with null parameter. equals()方法不适用于null参数。
The method needs to have an object or string as parameter. 该方法需要将对象或字符串作为参数。
public boolean equals(Object anObject)
Since null is not an object. 由于null不是对象。 Is null an Object?
对象是null吗? .
。
Also refer to java 7 documentation which says that equals will give result if and only if the object passed is not null. 另请参阅java 7文档,该文档说当当且仅当传递的对象不为null时,equals才会给出结果。
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object) http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.