如何在java中检查null值 [英] How to check for null value in java

查看:174
本文介绍了如何在java中检查null值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中。

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

We pass a null value to the function testFun. Compiles fine, but gives a nullPointerException in runtime.

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

Suppose the value of the actual argument being passed to testFun is generated from some process. Assume that mistakenly a null value is returned by that process and is fed to testFun. If such is the case, how does one validate that the value passed to the function is null or not?

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

One (weird) solution may be by assigning the formal parameter to some variable inside the function and then testing it. But if there are many variables passed to the function, that might become tedious and unfeasible. So, how does one check for null values in such a scenario?

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

By mistake I wrote || instead of | in the if condition. Runtime exception is now generated

推荐答案

编辑显示了有效代码和不代码的代码之间的区别。

The edit shows exactly the difference between code that works and code that doesn't.

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

This check always evaluates both of the conditions, throwing an exception if str is null:

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

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

Whereas this (using || instead of |) is short-circuiting - if the first condition evaluates to true, the second is not evaluated.

第15.24节的JLS描述 || ,以及 | 的/jls-15.html#jls-15.22.2\">第15.22.2节。第15.24节的介绍是重要的一点:

See section 15.24 of the JLS for a description of ||, and section 15.22.2 for binary |. The intro to section 15.24 is the important bit though:


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

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

这篇关于如何在java中检查null值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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