[英]Trying to understand code block combining Boolean and logical operators in java
Studying Java and this is a sample question I came across.学习 Java,这是我遇到的一个示例问题。 I think I understand the logic behind the answer but could somebody confirm whether I am understanding it correctly?
我想我理解答案背后的逻辑,但有人可以确认我是否正确理解了吗?
public class Q8 {
static boolean b1;
static boolean b2;
static boolean b3;
public static void main(String[] args) {
boolean trueOrFalse = (b1 = true) || (b2 = true) && (b3 = true); //Line 9
System.out.println(b1 + ", " + b2 + ", " + b3);
}
}
Program prints true, false, false
to console.程序向控制台打印
true, false, false
。
I understand that the class variables are assigned default values of false.我知道类变量被分配了 false 的默认值。
Am I right in saying that because b1 = true
is assigning a value of true to b1
instead of testing for equality like the question is laid out to have you believe, the or operator shortcuts leaving b2
and b3
as their default values and that's why true, false, false
prints to the console?上午我说得对,因为
b1 = true
被分配的真实的值b1
,而不是测试对像的问题平等奠定了有你相信的或操作的快捷方式离开b2
和b3
为默认值,这就是为什么true, false, false
打印到控制台?
Yes, that is correct.对,那是正确的。 You will set b1, evaluate and shortcut - so the rest is not set/evaluated.
您将设置 b1、评估和快捷方式 - 所以其余的不被设置/评估。
(b1 = true) 将 true 分配给 b1,然后由于 OR 运算符 || 跳过其余部分,因此 b2 和 b3 保留其默认的 false 值
Basically your code is a little bit different then how you as a human would read it.基本上,您的代码与您作为人类的阅读方式略有不同。 The compilers makes a few lines from your one line.
编译器从你的一行中生成几行。
// This is not exactly how it will be translated obviously, but this should make it a little bit more understandable for you.
if (trueOrFalse = (b1 = true))
else if (trueOrFalse = (b2 = true) && (b3 = true));
This means that b2 and b3 will always just be skipped这意味着 b2 和 b3 将始终被跳过
||
this is the OR operator and only checks the second statement when the first statement is false
When ever one of the sides of an OR operator is true, code will execute.这是 OR 运算符,仅当第一条语句为
false
时才检查第二条语句。当 OR 运算符的任何一方为真时,代码将执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.