Java From Beginner To Advanced

0% completed

Previous
Next
Bitwise Operators

Bitwise operators perform operations on the individual bits of integer values. They are used for low-level programming tasks, such as controlling hardware, setting flags, and optimizing performance. Bitwise operators work directly on the binary (bit) representations of numbers.

Bitwise Operators

OperatorDescriptionExample
&Bitwise AND: Sets each bit to 1 if both bits are 1a & b
|Bitwise OR: Sets each bit to 1 if one of the bits is 1a | b
^Bitwise XOR: Sets each bit to 1 if only one of the bits is 1a ^ b
~Bitwise NOT: Inverts all the bits~a

Example 1: Using Bitwise AND, OR, and XOR Operators

Below is an example that demonstrates how bitwise operators work using two integer values.

Java
Java

. . . .

Explanation:

  • Bitwise AND (&):
    • Calculation: 0101 & 0011 results in 0001 (only the rightmost bit is 1 in both).
    • Output: 1
  • Bitwise OR (|):
    • Calculation: 0101 | 0011 results in 0111 (if either bit is 1, the result is 1).
    • Output: 7
  • Bitwise XOR (^):
    • Calculation: 0101 ^ 0011 results in 0110 (bit is set to 1 only if the bits differ).
    • Output: 6

This example demonstrates how bitwise operators manipulate individual bits within integers. Experiment with these operators to understand how changing bits affects the outcome of expressions.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next