Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does a bitwise exclusive OR do in Java?

Tags:

java

scjp

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?

like image 690
Eslam Mohamed Mohamed Avatar asked Sep 06 '12 12:09

Eslam Mohamed Mohamed


People also ask

What is a bitwise exclusive?

The bitwise exclusive OR operator (in EBCDIC, the ‸ symbol is represented by the ¬ symbol) compares each bit of its first operand to the corresponding bit of the second operand. If both bits are 1 's or both bits are 0 's, the corresponding bit of the result is set to 0 .

What does XOR mean in Java?

The XOR logical operation, exclusive or, takes two boolean operands and returns true if, and only if, the operands are different. Conversely, it returns false if the two operands have the same value.

What is the purpose of Bitwise Operators in Java?

Bitwise operators are used to performing the manipulation of individual bits of a number. They can be used with any integral type (char, short, int, etc.). They are used when performing update and query operations of the Binary indexed trees.

What does bitwise XOR return?

The bitwise XOR operator ( ^ ) returns a 1 in each bit position for which the corresponding bits of either but not both operands are 1 s.


2 Answers

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
like image 57
Ilya Avatar answered Oct 11 '22 01:10

Ilya


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 ^

like image 30
Peter Lawrey Avatar answered Oct 11 '22 00:10

Peter Lawrey