如何检查java中的空值

时间:2012-08-26 19:46:01

标签: java

在此代码中。

public class Test {
     public static void testFun(String str) {
         if (str == null | str.length() == 0) {
             System.out.println("String is empty");
         } else { 
             System.out.println("String is not empty");
         }
     }
     public static void main(String [] args) {
         testFun(null);
    }
}

我们将空值传递给函数testFun。编译正常,但在运行时提供nullPointerException

假设传递给testFun的实际参数的值是从某个进程生成的。假设该进程错误地返回null值并将其提供给testFun。如果是这种情况,如何验证传递给函数的值是否为空?

一个(奇怪的)解决方案可能是将形式参数分配给函数内部的某个变量,然后对其进行测试。但是如果有许多变量传递给函数,那可能会变得乏味且不可行。那么,在这种情况下如何检查空值呢?

编辑:我错误地写了||而不是|在if条件下。现在生成运行时异常

6 个答案:

答案 0 :(得分:59)

编辑显示了正常运行的代码与不运行的代码之间的区别。

此检查始终评估条件的两个,如果str为空则抛出异常:

 if (str == null | str.length() == 0) {

然而(使用||代替|短路 - 如果第一个条件评估为true,则不评估第二个条件。

有关||的说明,请参阅JLS的section 15.24,对于二进制|,请参见section 15.22.2。第15.24节的介绍是重要的一点:

  

条件或运算符||运算符就像| (§15.22.2),但仅在其左侧操作数的值为假时才计算其右侧操作数。

答案 1 :(得分:5)

这里的问题是,在你的代码中程序调用'null.length()',如果传递给函数的参数为​​null,则不会定义该函数。这就是抛出异常的原因。

答案 2 :(得分:4)

问题是您使用的是按位或运算符:|。如果您使用逻辑或运算符||,您的代码将正常运行。

另见:
http://en.wikipedia.org/wiki/Short-circuit_evaluation
Difference between & and && in Java?

答案 3 :(得分:4)

您可以使用StringUtils

import org.apache.commons.lang3.StringUtils;

if (StringUtils.isBlank(str)) {

System.out.println("String is empty");

} else { 

System.out.println("String is not empty");

}

另请看这里:StringUtils.isBlank() vs String.isEmpty()

isBlank示例:

StringUtils.isBlank(null)      = true
StringUtils.isBlank("")        = true  
StringUtils.isBlank(" ")       = true  
StringUtils.isBlank("bob")     = false  
StringUtils.isBlank("  bob  ") = false

答案 4 :(得分:0)

更改以下行

if (str == null | str.length() == 0) {

进入

if (str == null || str.isEmpty()) {

现在您的代码将核心运行。确保str.isEmpty()str == null之后,因为对null调用isEmpty()会导致NullPointerException。由于Java在str == null为true时使用短路评估,因此不会评估str.isEmpty()

答案 5 :(得分:0)

和&每次都检查双方。

if(str == null | str.length()== 0)

在这里我们很可能获得NullPointerException

逻辑||和&&仅在必要时检查右侧。

但具有逻辑运算符

没有机会获得NPE,因为它不会检查RHS

相关问题