Java Quick Reference
  Language Fundamentals
  Operators and Assignments
  Flow Control and Exceptions
  Declarations and Access Control
  Garbage Collection
  Overloading and Overriding
  Threads
  The java.lang Package
  The java.util Package
  The java.awt Package
  The java.io Package
  References
  Miscellaneous Notes
  Tips & Traps
  Mock Exams

Operators and Assignments - Bitwise Operators

  • & AND, | OR, ^ exclusive OR
  • used for operations on integer and boolean values (see logical bitwise operators)
  • results are calculated bit-by-bit
  • binary numeric promotion rules apply
  • left associative
  • order of precedence: &, ^, |

& AND operator

  • returns a 1 if corresponding bits in both operands have a 1, otherwise returns a 0
  63    = 00000000 00000000 00000000 00111111
 252    = 00000000 00000000 00000000 11111100
          -----------------------------------
          00000000 00000000 00000000 00111100 -> 60

| OR operator

  • returns a 0 if corresponding bits in both operands are 0, otherwise returns a 1
  63    = 00000000 00000000 00000000 00111111
 252    = 00000000 00000000 00000000 11111100
          -----------------------------------
          00000000 00000000 00000000 11111111 -> 255

^ exclusive OR

  • returns a 0 if the corresponding bits of both operands are both 0 or both 1, otherwise returns a 1
  63    = 00000000 00000000 00000000 00111111
 252    = 00000000 00000000 00000000 11111100
          -----------------------------------
          00000000 00000000 00000000 11000011 -> 195

Also see

Example Code

Tips

  • precdence order is: & ^ |


Conversions Promotion Overflow Unary Prefix Arithmetic
  Bin/Hex/Octal Bitwise Shift Comparison Logical Assignment
  Cast Ternary String equals() Precedence Bit vs Logic
  Method Invocation