java - 与某些函数进行“或”运算为真

标签 java bit-manipulation

假设我有一个方法fun()

boolean fun()
{
    System.out.println("Hello World");
    return true;
}

我还有一个变量a

boolean a = true;

现在如果我写

boolean b = a || fun();

Java 会评估 || 的右侧还是会停止(因为 a 已经是 true,所以答案始终是将是 true,因此它不会评估 || 的右侧)。

最佳答案

请参阅 oracle 的文档:

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

因此,java 不会在这里计算 fun() 表达式,因为“短路”a 已经确定了最终值。

如果需要对 fun() 进行评估,可以采用以下快速修复方法:

boolean b = fun() || a;

boolean funValue = fun();
boolean b = a || funValue;

关于java - 与某些函数进行“或”运算为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56630942/

相关文章:

swift - 如何 swift 将 Int16 转换为两个 UInt8 字节

bit-manipulation - 无分支饱和度

c++ - 从位数组中提取任何更聪明的方法?

java - 在堆栈 View 中水平滑动

java - HttpsParameters 无法解析为类型

java - JAXB eclipse 错误 : There's no JAXB 2. 2 API 在类路径中

java - 将图标插入Java Swing JFrame

java - 按下按钮后显示用户输入

c - 按位 : different behaviour with negative input value

scala - 'BitSet' 存储位还是整数?