如何检查我的字符串是否等于空? [英] How to check if my string is equal to null?
问题描述
仅当我的字符串具有有意义的值时,我才想执行某些操作.所以,我试过了.
I want to perform some action ONLY IF my string has a meaningful value. So, I tried this.
if (!myString.equals("")) {
doSomething
}
还有这个
if (!myString.equals(null)) {
doSomething
}
还有这个
if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}
还有这个
if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}
还有这个
if ( myString.length()>0) {
doSomething
}
在所有情况下,我的程序 doSomething
尽管我的字符串是空的.它等于 null
.那么,这有什么问题?
And in all cases my program doSomething
in spite on the fact that my string IS EMPTY. It equals to null
. So, what is wrong with that?
添加:
我找到了问题的原因.该变量被声明为字符串,因此,分配给该变量的 null
被转换为 "null"
!所以,if (!myString.equals("null"))
有效.
I found the reason of the problem. The variable was declared as a string and, as a consequence, null
assigned to this variable was transformed to "null"
! So, if (!myString.equals("null"))
works.
推荐答案
if (myString != null && !myString.isEmpty()) {
// doSomething
}
<小时>
作为进一步的评论,您应该了解 equals
合同中的这个术语:
对于任何非空引用值x
,x.equals(null)
应该return false
.
For any non-null reference value
x
,x.equals(null)
shouldreturn false
.
与null
比较的方法是使用x == null
和x != null
.
The way to compare with null
is to use x == null
and x != null
.
此外,如果x == null
,x.field
和x.method()
会抛出NullPointerException
.
Moreover, x.field
and x.method()
throws NullPointerException
if x == null
.
这篇关于如何检查我的字符串是否等于空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!