Bitwise Operators

The bitwise operators, ~ (inversion), & (and), | (or), and ^ (exclusive-or) perform operations on integer values. The ~ operator is a unary operator, and the others are binary operators. Figure 3.2 summarizes how each operator performs its calculation.

Figure 3.2. How the bitwise operators work.

The ~ operator inverts the bits that make up the integer value. That is, 0 bits become 1 bits and 1 bits become 0 bits. For example, ~3 yields the value –4. It is calculated as follows:

  • 3 is represented as the binary int value 00000000 0000000000000000 00000011.

  • Inverting each of the bits yields 11111111 1111111111111111 11111100, which ...

Get Sun Certification Training Guide (310-025, 310-027): Java™ 2 Programmer and Developer Exams now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.