if语句检查是否为null,但仍然抛出NullPointerException [英] if statement checks for null but still throws a NullPointerException

查看:244
本文介绍了if语句检查是否为null,但仍然抛出NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此代码中.

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);
    }
}

我们将null值传递给函数testFun.可以正常编译,但是在运行时给出了NullPointerException,这是我所没有想到的.为什么会引发异常,而不是将if条件评估为true并显示字符串为空"?

We pass a null value to the function testFun. Compiles fine, but gives a NullPointerException in runtime, which I did not expect. Why is it throwing an exception, rather than evaluating the if condition to true and printing "String is empty"?

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

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?

推荐答案

所做的修改恰好显示了有效代码与无效代码之间的区别.

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.

有关JLS的第15.24节,请参见||第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.

这篇关于if语句检查是否为null,但仍然抛出NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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