首页 > 编程知识 正文

java中if语句多条件的用法,javaif语句判断三个条件怎么写

时间:2023-05-03 12:27:22 阅读:266515 作者:326

Lets say I have this:

if(bool1 && bool2 && bool3) {

...

}

Now. Is Java smart enough to skip checking bool2 and bool2 if bool1 was evaluated to false? Does java even check them from left to right?

I'm asking this because i was "sorting" the conditions inside my if's by the time it takes to do them (starting with the cheapest ones on the left). Now I'm not sure if this gives me any performance benefits because i don't know how Java handles this.

解决方案

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。