Java Bitwise Operations Advanced
In this page:
Bitwise AND and OR
Bitwise AND (&) sets each output bit only where both operands have a 1, and bitwise OR (|) sets each output bit where either operand has a 1 — both operate independently on every bit position.
Example: Bitwise AND and OR
public class Main {
public static void main(String[] args) {
System.out.println(5 & 3); // AND: 1
System.out.println(5 | 3); // OR: 7
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise XOR and Complement
Bitwise XOR (^) sets each output bit where exactly one operand has a 1 (but not both), and bitwise complement (~) flips every bit in a single value, turning each 0 into 1 and vice versa.
Example: Bitwise XOR and Complement
public class Main {
public static void main(String[] args) {
System.out.println(5 ^ 3); // XOR: 6
System.out.println(~5); // complement: -6
}
}
Login to try C/C++/Java/PHP code in the editor
Left Shift Operator
Left shift (<<) moves all bits toward the higher end, filling vacated positions with zeros — this is equivalent to multiplying by a power of two for each position shifted.
Example: Left Shift Operator
public class Main {
public static void main(String[] args) {
System.out.println(3 << 2); // 3 * 2^2 = 12
}
}
Login to try C/C++/Java/PHP code in the editor
Signed Right Shift Operator
Signed right shift (>>) moves bits toward the lower end while preserving the sign bit, so shifting a negative number keeps it negative — equivalent to dividing by a power of two while keeping sign correct.
Example: Signed Right Shift Operator
public class Main {
public static void main(String[] args) {
System.out.println(-8 >> 1); // sign preserved: -4
}
}
Login to try C/C++/Java/PHP code in the editor
Unsigned Right Shift Operator
Unsigned right shift (>>>) always fills vacated high-order bits with zero regardless of sign, which matters specifically when working with a negative number where you want a positive result instead of sign-preserving behavior.
Example: Unsigned Right Shift Operator
public class Main {
public static void main(String[] args) {
System.out.println(-8 >>> 1); // fills with zero, ignores sign
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: