Bitwise, Shift, Ternary & Operator Precedence
Use bitwise AND/OR/XOR, signed and unsigned shifts (<<, >>, >>>), the ternary operator (?:), and operator precedence rules.
- `&` (Bitwise AND):
1only if both bits are1. Useful for bitmasking ((num & 1) == 0checks even numbers). - `|` (Bitwise OR):
1if either bit is1. Useful for combining permission flags. - `^` (Bitwise XOR):
1if bits differ. Property:a ^ a == 0anda ^ 0 == a. - `~` (Bitwise Complement): Flips every bit (
~n == -(n + 1)).
Introduction
Bitwise and shift operators manipulate individual bits inside integer types (byte, short, int, long), which is foundational for permissions flags, hashing, compression, and low-level algorithms.
Bitwise & Shift Operators
- `&` (Bitwise AND):
1only if both bits are1. Useful for bitmasking ((num & 1) == 0checks even numbers). - `|` (Bitwise OR):
1if either bit is1. Useful for combining permission flags. - `^` (Bitwise XOR):
1if bits differ. Property:a ^ a == 0anda ^ 0 == a. - `~` (Bitwise Complement): Flips every bit (
~n == -(n + 1)). - `<<` (Left Shift): Shifts bits left, filling zeros on the right (multiplies by 2^n).
- `>>` (Signed Right Shift): Preserves the sign bit (divides by 2^n).
- `>>>` (Unsigned Right Shift): Shifts
0into the sign bit regardless of whether the number is negative.
Ternary Operator
condition ? exprIfTrue : exprIfFalse evaluates condition first and returns one of the two expressions. Unlike if-else, it is an expression that produces a value.
Precedence & Associativity
Unary > Multiplicative (*, /, %) > Additive (+, -) > Shift > Relational > Equality > Bitwise > Logical > Ternary > Assignment. When in doubt, add parentheses () for readability.
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)