Java Bitwise Operators

Java bitwise operators are used to perform bitwise operations on the binary representation of the operands. The following are the bitwise operators in Java:

  1. Bitwise AND: &
    The bitwise AND operator performs a bitwise AND operation on the binary representation of the operands.
int a = 0b1010; // binary literal for decimal 10
int b = 0b1100; // binary literal for decimal 12
int result = a & b; // result is 0b1000, or decimal 8
So‮cru‬e:www.theitroad.com
  1. Bitwise OR: |
    The bitwise OR operator performs a bitwise OR operation on the binary representation of the operands.
int a = 0b1010; // binary literal for decimal 10
int b = 0b1100; // binary literal for decimal 12
int result = a | b; // result is 0b1110, or decimal 14
  1. Bitwise XOR: ^
    The bitwise XOR operator performs a bitwise exclusive OR operation on the binary representation of the operands.
int a = 0b1010; // binary literal for decimal 10
int b = 0b1100; // binary literal for decimal 12
int result = a ^ b; // result is 0b0110, or decimal 6
  1. Bitwise NOT: ~
    The bitwise NOT operator performs a bitwise complement operation on the binary representation of the operand.
int a = 0b1010; // binary literal for decimal 10
int result = ~a; // result is 0b11111111111111111111111111110101, or decimal -11
  1. Left shift: <<
    The left shift operator shifts the binary representation of the left operand to the left by the number of positions specified by the right operand.
int a = 0b1010; // binary literal for decimal 10
int result = a << 2; // result is 0b101000, or decimal 40
  1. Right shift: >>
    The right shift operator shifts the binary representation of the left operand to the right by the number of positions specified by the right operand. The sign bit is preserved for signed values.
int a = -10;
int result = a >> 2; // result is -3
  1. Zero-fill right shift: >>>
    The zero-fill right shift operator shifts the binary representation of the left operand to the right by the number of positions specified by the right operand. The sign bit is filled with a 0.
int a = -10;
int result = a >>> 2; // result is 1073741821