假设我有一个方法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/