Java中的按位异或是什么?
鉴于:
public class Spock { public static void main(String[] args) { Long tail = 2000L; Long distance = 1999L; Long story = 1000L; if ((tail > distance) ^ ((story * 2) == tail)) { System.out.print("1"); } if ((distance + 1 != tail) ^ ((story * 2) == distance)) { System.out.print("2"); } } }
为什么这个示例代码不输出任何内容?
首先,如果你得到true ^ true = false
在第二个,如果你得到false ^ false = false
因为^
– 是OR exclusive
opeartor,它的意思是
true ^ true = false true ^ false = true false ^ true = true false ^ false = false
您正在使用布尔异或,这与!=
非常相似。 在第一种情况下,两种情况都是正确的,而在第二种情况下,两种情况都是错误的,因此都不采用分支。 (您可以在IDE中使用调试器进行检查)
唯一真正的区别是!=
优先级高于&
,高于^
来自http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.22.2
For ^, the result value is true if the operand values are different; otherwise, the result is false.
它不会打印任何内容,因为当XOR运算符与布尔参数(而不是整数)一起使用时,如果两个操作数中只有一个为true
则只返回true
。
在你的第一个中, if
两个部分都评估为true
和true ^ true == false
在你的第二个, if
两个部分评估为false
和false ^ false == false