Reputation: 31
I would assume in Java all the bit-wise operators have the same precedence. However, in fact the bit-wise operator AND (&) has higher precedence than the bit-wise operator OR (|). See the program below:
public class HelloWorld {
public static void main(String[] args) {
int a = 1 | 2 ^ 3 & 5;
int b = ((1 | 2) ^ 3) & 5;
int c = 1 | (2 ^ (3 & 5));
System.out.print(a + "," + b + "," + c);
}
}
The result of the above program is 3,0,3. So it also proves that XOR (^) has higher precedence.
Why does XOR (^) have higher precedence than OR (|) according to the result of the above result? How do they define the precedence?
Upvotes: 3
Views: 1330
Reputation: 5612
Because &
is defined to have higher precedence than ^
, and ^
is defined to have higher precedence than |
.
Look at Oracle's Java tutorial.
Upvotes: 1
Reputation: 3302
In Java, bitwise operators have different precedences as defined by the Java specification:
These [bitwise] operators have different precedence, with & having the highest precedence and | the lowest precedence.
So &
comes before ^
and ^
comes before |
.
Upvotes: 1