简体   繁体   English

是否可以保证在Java中如何对逻辑进行分组?

[英]is there a guarantee of how logic will be grouped in Java?

boolean A = true;
boolean B = false;
boolean C = true;


if(A == true && B == true || C == true);

Is there any reason that I can take for granted that this will evaluate to false? 我有什么理由可以认为这将为假吗? (or true?) (或者是真的?)

I understand that the best thing here is to wrap the two params that matter in their own parens, but I'm curious about the Java VM and if it's consistent (especially in the case of Delvik). 我知道最好的办法是将重要的两个参数包装在自己的括号内,但是我对Java VM及其是否一致(尤其是Delvik)感到好奇。 Does it see that B is false and quit (because of the && which seems to require it to be true, if reading it from left to right) or does it natively group the two items on the sides of the || 它是否看到B为假并退出(因为&&似乎要求它为真,如果从左到右读取它),或者它本机地将||两侧的两项组合在一起 and keep looking to see if C is true (in which case the entire statement ends up being true). 并继续寻找C是否为真(在这种情况下,整个语句最终都为真)。

It's not about the VM, the VM works on a lower level and doesn't even see expressions in the same order as you write them in Java. 这与虚拟机无关,虚拟机工作在较低级别,甚至看不到用Java编写表达式的顺序相同的表达式。 What is important here is operator precedence: 这里重要的是运算符优先级:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

Just like they teach you "multiplication before addition" at school, there's a precedence for all the other operators as well. 就像他们在学校教您“加法前乘法”一样,所有其他运算符也具有优先权。 In Java's case, && has higher precedence than || 在Java的情况下, &&优先级高于|| . Therefore 因此

(A == true && B == true || C == true)

is equivalent to 相当于

((A == true && B == true) || C == true)

But in reality, just like you said, use those parenthesis. 但是实际上,就像您说的那样,请使用这些括号。 It makes it easier to read. 它使阅读更容易。

Free protip: == true is superfluous. 免费提示: == true是多余的。 It doesn't do anything. 它什么也没做。 Replace A == true with just A . 更换A == true只有A

The order is well defined on the Java language level (so it will work on both JVM and Dalvik). 该顺序在Java语言级别上定义良好(因此,它将在JVM和Dalvik上均适用)。

Basically 基本上

  • left to right 左到右
  • shortcut operators cut short 快捷键运算符缩短了
  • there is operator precendence between && and || &&和||之间有运算符优先

The latter point I personally can never remember or at least reliably parse quickly, so I always use parens to be explicit. 我个人不记得后者,或者至少不能可靠地快速解析,因此我总是使用parens来明确表示。 Makes it easier to read. 使其更易于阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM