为什么&&"的右侧不正确运营商评估? [英] Why isn't the right side of && operator evaluated?

查看:48
本文介绍了为什么&&"的右侧不正确运营商评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小疑问.为什么以下代码的输出为 1 ?为什么不 3 ?

Small doubt. Why is the output of the following code 1? Why not 3?

int i = 0;
boolean t = true, f = false, b;
b = (t && ((i++) == 0));
b = (f && ((i+=2) > 0));
System.out.println(i);

推荐答案

条件和运算符-&& -是短路的.如果左操作数为false,则不会评估右操作数.这就是为什么从未对((i + = 2)> 0)进行评估,而 i 仍为1的原因.

the Conditional-And operator - && - is short circuit. It doesn't evaluate the right operand if the left operand is false. That's why ((i+=2) > 0) is never evaluated, and i remains 1.

JLS 15.23 :

&&运算子就像&(§15.22.2),但仅当其左操作数的值为true时,才对其右操作数求值.

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.

这篇关于为什么&&"的右侧不正确运营商评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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