Java对对象进行空检查 [英] Java null check on object

查看:52
本文介绍了Java对对象进行空检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这是一个简单的问题,我对此没有任何问题,但我只是想确定一下.我这样做是正确的吗?

Okay, its a simple question, I dont have any problem with it but I just want to be sure. Is it correct if I do something like this ?

if (person != null && person.getAge > 20) {...}

我可以这样做吗?空检查和对象访问在同一行上?这样对吗?或者我必须在null检查语句上做一个内部语句,例如:

can I do this? null check and object access on the same line? is this correct? or I have to make an inner statement on the null check statement like:

if (person != null)
{
    if (person.getAge() > 20) {...}
}

imo,第一个声明不会抛出NPE,但我需要专业人士的反馈...

imo, the first statement wouldnt throw a NPE, but I needed feedback from professionals...

通常我的问题是,在带有&&的if语句上,如果第一个布尔值是false,那么JVM会停止执行if语句还是将全部检查?

Generally my question is that, on if statements with &&, if the first boolean is false, will the JVM stop executing the if statement or it will check it all ?

推荐答案

是.运算符&& || 被称为短路运算符.这意味着,一旦知道答案(从左到右读取),就不会评估条件中的其他语句.在您的情况下,只要 person!= null 部分的计算结果为 false ,则无论其他语句如何,都将保证整个条件为false,因此, person.getAge>20 将不会被评估,也不会引发异常.同样,如果使用 || ,并且第一部分的评估结果为 true ,则第二部分将不会评估,因为总的条件保证为 true .

Yes. The operators && and || are what are known as short circuiting operators. This means that as soon as the answer is known, reading from left to right, the other statements in the condition are not evaluated. In your case, as soon as person != null part evaluates to false, the whole condition will be guaranteed to be false regardless of the other statements, so person.getAge > 20 will not be evaluated and will not throw an exception. Similarly, if you use ||, and the first part evaluates to true, the second part will not be evaluated because the overall conditional is guaranteed to be true at that point.

这篇关于Java对对象进行空检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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