gpt4 book ai didi

java - & vs && -- 第一种情况如何使用?

转载 作者:行者123 更新时间:2023-12-02 17:35:41 24 4
gpt4 key购买 nike

(a > b) & (c < d), the components are evaluated left to right, so (a > b) is evaluated first. If (a > b) is false, the entire expression is false regardless of the result of the component (r < d). Nevertheless, the component (c < d) will still be evaluated. However, in the expression (a > b) && (c < d), the component (c < d) will not be evaluated if (a > b) evaluates to false. This is known as short circuiting.

在一本 Java 书中看到这一段。我以前一直用各种语言编程,但我从未发现需要“&”。如果知道最终结果不受第二个语句的影响,为什么还要评估第二个语句呢?有什么用吗?这是由于历史原因吗?

同样的问题适用于 |和 ||也是如此。

最佳答案

&& operator由 Java 语言规范定义,用于执行短路评估。

但是,& 运算符不是 even when applied to boolean arguments .

如果其中一个参数具有您不希望短路的副作用,您可以利用这一点。然而,根据我的经验,这种情况并不常见,您将面临有人“修复”它的风险。最好分成步骤。例如,代替:

if ( foo() & bar() ) {... }

你可以说:

boolean isFoo = foo();
boolean isBar = bar();
if ( isFoo && isBar ) { ... }

关于java - & vs && -- 第一种情况如何使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7814449/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com