What does a bitwise exclusive OR do in Java?
Asked Answered
A

4

6

Given:

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");
        }
    }
}

Why this sample code doesn't output anything?

Atomic answered 6/9, 2012 at 12:1 Comment(0)
B
11

In first if you get true ^ true = false
In second if you get false ^ false = false
becouse ^ - is OR exclusive opeartor, it's means

true ^ true = false  
true ^ false = true 
false ^ true = true 
false ^ false = false
Bergama answered 6/9, 2012 at 12:5 Comment(1)
So you can think of it like this then. If True represents a positive and False represents a negative then a negative times a positive equals a positive, a negative times a negative equals a negative, and a positive times a positive equals a negative....it's completely backwards :)Vaginal
T
9

You are using boolean exclusive OR and this is much the same as !=. In the first case, both conditions are true and in the second, both conditions are false so neither branch is taken. (You can check this with the debugger in your IDE)

The only real difference is that != has higher precedence than & which is higher than ^

Treulich answered 6/9, 2012 at 12:5 Comment(0)
H
4

From 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.

Heterosporous answered 6/9, 2012 at 12:7 Comment(0)
H
1

It doesn't print anything because when the XOR operator is used with boolean arguments (as opposed to integers) will only return true if exactly one of the 2 operands is true.

In your first if both parts evaluate to true and true ^ true == false

In your second if both parts evaluate to false and false ^ false == false

Heddi answered 6/9, 2012 at 12:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.