+ 2
I Don't understand the use of ^ in Java
I have this code. int a = 10; int b = 20; int c = 6; System.out.println(a > b ^ a > c); The output is true, I don't understand what ^ does, why is the output true? what is the main function of ^ when is inside of one conditional?
2 Answers
+ 5
^ is bitwise exclusive OR operator .
It's truth table is:
P Q R
0 0 0
0 1 1
1 0 1
1 1 0
So it gives result 1(true) if and only if one of the two propositions is 1(true)
Also priority of operator ^ is less than both < and > so first a>b and a>c get evaluated.
a>b is false (10<20 is false)
a>c is true (10>6 is true)
now false ^ true corresponds to column
0 1 in the truth table. so answer is 1(true)
+ 1
^ is a bitwise XOR its operator precedence is lower than that of < or > so it will happen after those complete.
a > b = false
a > c = true
false ^ true = true
false = 0
true = 1
XOR Table
^ 0 1
0 0 1
1 1 0
false ^ false = false
true ^ true = false
true ^ false = true
false ^ true = true
Basically with an XOR if the comparing bits are the same the resulting bit is 0 otherwise 1.