检查条件是否为“null”

时间:2013-02-09 10:59:47

标签: java android string if-statement null

我对检查null条件有疑问。例如:

if(some conditon)
value1= value;  //value1 is string type
else 
value1= "";

类似地,其他4个其他字符串值具有相似的条件。 我需要的是我想检查所有这5个字符串值是否为null,为了做一些其他特定的部分。 我这样做了

if(value1 == null)
{
}

但是pgm控件没有进入循环eventHough值1 =“”。 然后我试过

if(value1 ==""){
} 

这也没有用。

我们不能检查null和“”值一样吗? 任何人都可以帮助我吗?

6 个答案:

答案 0 :(得分:9)

如果要检查String是否为null,则使用

if (s == null)

如果要检查字符串是否为空字符串,请使用

if (s.equals(""))

if (s.length() == 0)

if (s.isEmpty())

空字符串是空字符串。它不是空的。并且==绝不能用于比较字符串内容。 ==测试两个变量是否引用同一个对象实例。如果它们包含相同的字符,则不会。

答案 1 :(得分:5)

要检查String上的“is not null”和“is not empty”,请使用静态

TextUtils.isEmpty(stringVariableToTest)

答案 2 :(得分:3)

看起来你想检查String是否为空。

if (string.isEmpty())

您无法通过执行if (string == "")来检查,因为您正在比较String对象。它们永远不会相同,因为你有两个不同的对象。要比较字符串,请使用string.equals()

答案 3 :(得分:1)

当您使用String时,请始终使用.equals

equals()函数是Object类的一个方法,应由程序员覆盖。

如果你想检查字符串是否为if (string.isEmpty()),那么你也可以尝试if (string.equals(null))

答案 4 :(得分:1)

您可以使用:

我们可以通过两种方式检查字符串是否为空:

  • if(s != null && s.length() == 0)
  • if(("").equals(s))

答案 5 :(得分:0)

更喜欢以下。

String str;
if(str.length() > 0)
{
     Log.d("log","str is not empty");
}
else
{
     Log.d("log","str is empty");
}