Java运算符优先级Operator Precedence
Operators | Precedence |
---|---|
postfix | expr++ expr-- |
unary | ++expr --expr +expr -expr ~ ! |
multiplicative | * / % |
additive | + - |
shift | << >> >>> |
relational | < > <= >= instanceof |
equality | == != |
bitwise AND | & |
bitwise exclusive OR | ^ |
bitwise inclusive OR | | |
logical AND | && |
logical OR | || |
ternary | ? : |
assignment | = += -= *= /= %= &= ^= |= <<= >>= >>>= |
BooleanOperators
boolean a, b;
Operation | Meaning | Note |
---|---|---|
a && b | logical AND | short-circuiting |
a || b | logical OR | short-circuiting |
a & b | boolean logical AND | not short-circuiting |
a | b | boolean logical OR | not short-circuiting |
a ^ b | boolean logical exclusive OR | |
!a | logical NOT |
For &, the result value is true if both operand values are true; otherwise, the result is false.
For ^, the result value is true if the operand values are different; otherwise, the result is false.
For |, the result value is false if both operand values are false; otherwise, the result is true.
证明与&或|非~的操作顺序
final int value1 = ~0xffff_0000 & 0xffff_0000;
//先~的话结果是:0x0000_0000, 先&的话结果是:0x0000_ffff
final int value2 = ~0xffff_0000 | 0xffff_0000;
//先~的话结果是:0xffff_ffff,先|的话结果是:0x0000_ffff
final int value3 = 0x00ff_0000 & 0xff00_ffff | 0x0000_ff00;
//先&的话结果是:0x0000_ff00, 先|的话结果是:0x0000_0000
final int value4 = 0x0000_ff00 | 0xff00_ffff & 0x00ff_0000;
//先&的话结果是:0x0000_ff00, 先|的话结果是:0x0000_0000
assertEquals(0x0000_0000, value1);
assertEquals(0xffff_ffff, value2);
assertEquals(0x0000_ff00, value3);
assertEquals(0x0000_ff00, value4);