Bitwise Operators in Java with Examples

Bitwise operators in Java are special symbols that perform operations directly on the binary representation (0s and 1s) of integer values. For example:

  • Number 5 in binary = 0101
  • Number 3 in binary = 0011

When a bitwise operator is applied, Java processes these binary digits individually. Bitwise operators are widely used in programming for:

  • Memory optimization
  • Data compression
  • Cryptography
  • Network programming
  • Low-level device control.

Types of Bitwise Operators in Java

Java provides six main bitwise operators:

  • Bitwise AND (&)
  • Bitwise OR (|)
  • Bitwise XOR (^)
  • Bitwise Complement (~)
  • Left Shift (<<)
  • Right Shift (>>)
  • Unsigned Right Shift (>>>)

Let’s explore each operator in detail with syntax, examples, and explanations.

Bitwise AND Operator (&)

The bitwise AND operator is a binary operator that compares each bit of two numbers. It is represented by the single ampersand symbol &. If both corresponding bits are 1, the result is 1. Otherwise, the result is 0. This rule can be perfectly summarized by what’s called a truth table:

A (First Bit)B (Second Bit)A & B (Result)
000
010
100
111

Syntax

int result = operand1 & operand2;

Example:

public class BitwiseANDEx {
  public static void main(String[] args) {
     int a = 12;  // Binary: 1100
     int b = 10;  // Binary: 1010
     int result = a & b;
        
     System.out.println("a & b = " + result);
     System.out.println("Binary: " + Integer.toBinaryString(a) + 
                         " & " + Integer.toBinaryString(b) + 
                         " = " + Integer.toBinaryString(result));
  }
}
Output:
     a & b = 8
     Binary: 1100 & 1010 = 1000

Step-by-Step Explanation:

Let’s take the decimal numbers 12 and 10.

1. Convert to Binary:

  • 12 in 4-bit binary is 1100
  • 10 in 4-bit binary is 1010

2. Line up the bits and apply the & rule to each column:

  1 1 0 0  (12 - Decimal)
& 1 0 1 0  (10 - Decimal)
-------------
  1 0 0 0  (8 - Decimal Result)
  • Rightmost bit (LSB): 0 & 0 = 0
  • Next bit: 0 & 1 = 0
  • Next bit: 1 & 0 = 0
  • Leftmost bit (MSB): 1 & 1 = 1

3. Convert the result back to decimal:

  • The resulting binary 1000 equals 8 in decimal.

Bitwise OR (|) Operator

The bitwise OR operator in Java is a binary operator that compares each bit of two integers.

  • It returns 1 if at least one of the bits is 1.
  • It returns 0 only if both bits are 0.

In other words, the bitwise OR operator performs a logical inclusive OR operation on each corresponding pair of bits in the binary representations of two integers. It is represented by the single vertical bar symbol (|).

Syntax

int result = operand1 | operand2;

Truth Table

A (First Bit)B (Second Bit)A | B (Result)
000
011
101
111

Example:

public class BitwiseORExample {
 public static void main(String[] args) {
    int a = 12;
    int b = 10;
    int result = a | b; // Performs the bitwise OR.

    System.out.println("a | b = " + result); // Output: 14
    System.out.println("Binary: " + Integer.toBinaryString(a) + 
                         " | " + Integer.toBinaryString(b) + 
                         " = " + Integer.toBinaryString(result));
    }
}
Output:
      a | b = 14
      Binary: 1100 | 1010 = 1110

Step-by-Step Explanation:

Let’s take the decimal numbers 12 and 10.

1. Convert to Binary:

  • 12 in 4-bit binary is 1100
  • 10 in 4-bit binary is 1010

2. Line up the bits and apply the | rule to each column:

  1 1 0 0  (12 - Decimal)
| 1 0 1 0 (10 - Decimal)
-------------
1 1 1 0 (14 - Decimal Result)
  • Rightmost bit (LSB): 0 | 0 = 0
  • Next bit: 0 | 1 = 1
  • Next bit: 1 | 0 = 1
  • Leftmost bit (MSB): 1 | 1 = 1

3. Convert the result back to decimal:

  • The resulting binary 1110 equals 14 in decimal number system.

Bitwise XOR Operator (^)

The bitwise XOR (exclusive OR) operator in Java is a binary operator that performs a logical operation on each corresponding pair of bits:

  • If the two bits are different, the result is 1.
  • If the two bits are the same, the result is 0.

The bitwise XOR (exclusive OR) operator is represented by the caret symbol (^). The “exclusive” part of the name is important—it means “one or the other, but not both”.

Syntax

int result = operand1 ^ operand2;

Truth Table

A (First Bit)B (Second Bit)A ^ B (Result)
000
011
101
110

Example:

public class BitwiseXOREx {
  public static void main(String[] args) {
     int a = 12;
     int b = 10;
     int result = a ^ b; // Performs the bitwise XOR

     System.out.println("a ^ b = " + result);
     System.out.println("Binary: " + Integer.toBinaryString(a) + 
                         " ^ " + Integer.toBinaryString(b) + 
                         " = " + Integer.toBinaryString(result));
  }
}
Output:
      a ^ b = 6
      Binary: 1100 ^ 1010 = 110

Step-by-Step Explanation: Let’s use the decimal numbers 12 and 10.

1. Convert to Binary:

  • 12 in 4-bit binary is 1100
  • 10 in 4-bit binary is 1010

2. Line up the bits and apply the ^ rule to each column:

  1 1 0 0  (12 - Decimal)
^ 1 0 1 0 (10 - Decimal)
-------------
0 1 1 0 (6 - Decimal Result)
  • Rightmost bit (LSB): 0 ^ 0 = 0
  • Next bit: 0 ^ 1 = 1
  • Next bit: 1 ^ 0 = 1
  • Leftmost bit (MSB): 1 ^ 1 = 0

3. Convert the result back to decimal:

  • The resulting binary 0110 equals 6 in decimal number system.

Bitwise Complement Operator (~)

The bitwise complement operator is a unary operator in Java, meaning it works on a single operand. This operator is represented by the tilde symbol (~). It is also commonly called the bitwise NOT operator.

The bitwise complement operator flips every single bit in the binary representation of a number.

  • It changes every 0 to 1.
  • It changes every 1 to 0.

Syntax

int result = ~operand;

Truth Table

A (Input Bit)~A (Result)
01
10

Example:

public class BitwiseComplementExample {
 public static void main(String[] args) {
    int a = 6;
    int result = ~a;
    System.out.println("~a = " + result); // Output: -7
    System.out.println("Binary: ~" + Integer.toBinaryString(a) + 
                         " = " + Integer.toBinaryString(result));
  }
}
Output:
      ~a = -7
      Binary: ~110 = 11111111111111111111111111111001

Step-by-Step Explanation:

Let’s take the decimal number 6.

1. Convert to Binary:

  • 6 in 8-bit binary is 00000110

2. Apply the ~ operator to each bit:

  • ~00000110 becomes 11111001

If you convert 11111001 directly back to decimal, we get 249. But if you run this in Java, you get a different result. Wait, -7? And why is the binary output so long? This is the most important concept to understand.

Key Concept: Two’s Complement and Integer Representation

Java uses two’s complement system to represent negative integers. The number of bits used is 32 (for an int), not 8.

1. The Real Binary of 6: 00000000 00000000 00000000 00000110

2. Apply the bitwise complement operator ~ that flips all bits: 11111111 11111111 11111111 11111001

This is the binary representation of the result. What does this represent?

In two’s complement, a number is negative if the leftmost bit (i.e. the sign bit) is 1. The result 111…11001 has a sign bit of 1, so it’s a negative number.

How to find its value?

To find the decimal value of a negative two’s complement number, you apply the same process: complement all bits and add 1.

Step 1: Complement the bits: 00000000 00000000 00000000 00000110 (which is 6)

Step 2: Add 1: 6 + 1 = 7

Conclusion: The original binary string 111…11001 must therefore represent -7. This is why ~6 equals -7. There’s a mathematical symmetry: The complement of any integer N is always -N – 1.

  • ~6 = -7 which is -6 – 1
  • ~-10 = 9 which is -(-10) – 1 = 10 – 1
  • ~0 = -1

Left Shift Operator (<<)

The left shift operator (<<) in Java is a bitwise operator that moves all the bits of a number’s binary representation to the left side by the number of positions you specify. When bits move out from the left, they are thrown away. The vacant bit positions on the right are filled with zeros.

How it works step by step:

  • Write the number in binary form (0s and 1s).
  • Move each bit to the left by n positions.
  • Discard any bits that go out on the left.
  • Fill the new empty places on the right with 0s.

Syntax

int result = operand << numberOfPositions;

In the above syntax,

  • operand is the number whose bits you want to shift.
  • numberOfPositions is the non-negative number of positions to shift left.

Example:

public class LeftShiftExample {
  public static void main(String[] args) {
     int number = 5;
     int shift = 2;
     int result = number << shift;
     System.out.println(number + " << " + shift + " = " + result);
      
  // Format the output to show full 32 bits for clarity.
     System.out.println("Binary: " + String.format("%32s", Integer.toBinaryString(number)).replace(' ', '0'));
     System.out.println(" << " + shift + " ");
     System.out.println("Binary: " + String.format("%32s", Integer.toBinaryString(result)).replace(' ', '0'));
  }
}
Output:
      5 << 2 = 20
      Binary: 00000000000000000000000000000101
      << 2
      Binary: 00000000000000000000000000010100  

Step-by-Step Explanation:

Let’s take the decimal number 5 and shift it left by 2 positions (5 << 2).

1. Convert to Binary:

  • 5 in 8-bit binary is 00000101

2. Perform the Left Shift by 2:

Original (8 bits): [0][0][0][0][0][1][0][1]
Shifted (conceptual): [0][0][0][1][0][1][0][0] // The last two spots become 0
Result (8 bits): [0][0][0][1][0][1][0][0] // This is 20 in decimal

The result is the binary number 00010100.

3. Convert to Decimal:

  • 00010100 in binary equals 20 in decimal.

Right Shift Operator (>>)

The right shift operator (>>) in Java is a bitwise operator that moves all the bits of a number’s binary representation a specified number of positions to the right. This operator is also known as the signed right shift or arithmetic right shift.

The bits are shifted right. The empty bit positions on the left are filled based on the sign bit (the leftmost bit):

  • If the number is positive (sign bit is 0), the left bits are filled with 0s.
  • If the number is negative (sign bit is 1), the left bits are filled with 1s.

This preserves the sign of the original number.

Syntax

int result = operand >> numberOfPositions;

In the above syntax,

  • operand represents the number whose bits you want to shift.
  • numberOfPositions represents the non-negative number of positions to shift right.

How Does it Work?

The operation for a given operand and numberOfPositions n positions:

  • Convert the operand to its binary form.
  • Use two’s complement for negatives.
  • Move every bit n places to the right. The rightmost bits are discarded.
  • Fill the new empty bit positions on the left with the sign bit 0 for positive, and 1 for negative.

Example:

public class RightShiftExample {
  public static void main(String[] args) {
     int positive = 12;
     int negative = -12;
     int shift = 2;

     int resultPos = positive >> shift;
     int resultNeg = negative >> shift;
     System.out.println(positive + " >> " + shift + " = " + resultPos);
     System.out.println(negative + " >> " + shift + " = " + resultNeg);

  // Show binary representation of the numbers.
     System.out.println("Binary of " + positive + ": " + String.format("%32s", Integer.toBinaryString(positive)).replace(' ', '0'));
     System.out.println("Binary of " + negative + ": " + Integer.toBinaryString(negative)); // Java shows the full 32 bits for negatives
     System.out.println("Binary of result (" + resultNeg + "): " + Integer.toBinaryString(resultNeg));
    }
}
Output:
      12 >> 2 = 3
     -12 >> 2 = -3
      Binary of 12: 00000000000000000000000000001100
      Binary of -12: 11111111111111111111111111110100
      Binary of result (-3): 11111111111111111111111111111101

Step-by-Step Explanation:

1. Positive Number (12 >> 2)

  • Convert to Binary: 12 in 8-bit binary is 00001100
  • Perform the Right Shift by 2:
Original:  [0][0][0][0][1][1][0][0]
Shifted:   [0][0][0][0][0][0][1][1]  // The last two spots are lost, new bits are 0.
Result:    [0][0][0][0][0][0][1][1]  // This is 3 in decimal number system.
  • Convert to Decimal: 00000011 in binary equals 3 in decimal.

2. Negative Number (-12 >> 2)

  • Convert to Binary (Two’s Complement):
    • First, find the binary of 12: 00001100
    • Invert all bits: 11110011
    • Add 1: 11110100 (This is the 8-bit two’s complement representation of -12).
  • Perform the Right Shift by 2:
Original:  [1][1][1][1][0][1][0][0]  (-12)
Shifted:   [1][1][1][1][1][1][0][1]  // Last two bits lost, new bits are 1.
Result:    [1][1][1][1][1][1][0][1]  // This is -3 in decimal.

How do we know it’s -3?

The result is negative. To find its value, invert the bits and add 1: 11111101 -> invert to 00000010 -> add 1 -> 00000011 (which is 3). So, the original binary representation 11111101 represents -3.

Unsigned Right Shift Operator (>>>)

The unsigned right shift operator (>>>) in Java is a bitwise operator that moves all the bits of a number’s binary representation a specified number of positions to the right. This operator is also known as the logical right shift.

The bits are shifted right. The vacant bit positions on the left are always filled with 0s, regardless of the sign bit. This is the important difference between unsigned right shift operator >>> and the signed right shift >>.

Syntax

int result = operand >>> numberOfPositions;

In the above syntax,

  • operand represents the number whose bits you want to shift.
  • numberOfPositions represents the non-negative number of positions to shift right.

How Does it Work?

The operation for a given operand and numberOfPositions n positions:

  • Convert the operand to its binary representation.
  • Move every bit n places to the right. The rightmost bits are discarded.
  • Fill the new empty bit positions on the left with 0, even if the original number was negative.

Example:

public class UnsignedRightShiftExample {
 public static void main(String[] args) {
    int positive = 12;
    int negative = -12;
    int shift = 2;

    int resultPos = positive >>> shift;
    int resultNeg = negative >>> shift;
    System.out.println(positive + " >>> " + shift + " = " + resultPos);
    System.out.println(negative + " >>> " + shift + " = " + resultNeg);

 // Show binary representation to see the zero-filling.
    System.out.println("Binary of " + positive + ": " + String.format("%32s", Integer.toBinaryString(positive)).replace(' ', '0'));
    System.out.println("Binary of " + negative + ": " + String.format("%32s", Integer.toBinaryString(negative)).replace(' ', '0'));
    System.out.println("Binary of result (" + resultNeg + "): " + String.format("%32s", Integer.toBinaryString(resultNeg)).replace(' ', '0'));
  }
}
Output:
      12 >>> 2 = 3
     -12 >>> 2 = 1073741821
      Binary of 12: 00000000000000000000000000001100
      Binary of -12: 11111111111111111111111111110100
      Binary of result (1073741821): 00111111111111111111111111111101

Example: Combining All Java Bitwise Operators

public class BitwiseAdvancedExample {
  public static void main(String[] args) {
      int a = 12;   // 1100
      int b = 25;   // 11001

      System.out.println("a & b = " + (a & b));  // AND
      System.out.println("a | b = " + (a | b));  // OR
      System.out.println("a ^ b = " + (a ^ b));  // XOR
      System.out.println("~a = " + (~a));        // NOT
      System.out.println("a << 2 = " + (a << 2));// Left shift
      System.out.println("b >> 2 = " + (b >> 2));// Right shift
  }
}
Output:
      a & b = 8
      a | b = 29
      a ^ b = 21
      ~a = -13
      a << 2 = 48
      b >> 2 = 6

Advanced Bitwise Operations and Practical Applications

Example 1: Checking if a Number is Even or Odd

public class EvenOddCheck {
 public static void main(String[] args) {
     int num = 15;
     if ((num & 1) == 0) {
         System.out.println(num + " is even");
     } else {
         System.out.println(num + " is odd");
     }
  }
}
Output:
      15 is odd

Example 2: Swapping Two Numbers Without Temporary Variable

public class SwapNumbers {
  public static void main(String[] args) {
     int a = 5, b = 9;
     System.out.println("Before swap: a = " + a + ", b = " + b);
        
     a = a ^ b;
     b = a ^ b;
     a = a ^ b;
     System.out.println("After swap: a = " + a + ", b = " + b);
  }
}
Output:
      Before swap: a = 5, b = 9
      After swap: a = 9, b = 5

Example 3: Checking Power of Two

public class PowerOfTwoCheck {
  public static void main(String[] args) {
      int[] numbers = {8, 10, 16, 31};
        
      for (int num : numbers) {
          if ((num & (num - 1)) == 0) {
              System.out.println(num + " is a power of two");
          } else {
              System.out.println(num + " is not a power of two");
          }
       }
   }
}
Output:
      8 is a power of two
      10 is not a power of two
      16 is a power of two
      31 is not a power of two

Bitwise Operator Precedence

Bitwise operators have the following precedence (from highest to lowest):

  • ~ (complement)
  • <<, >>, >>> (shifts)
  • & (AND)
  • ^ (XOR)
  • | (OR)

Always use parentheses to explicitly specify evaluation order when you are combining multiple operators.

Conclusion

In this tutorial, you learned bitwise operators in Java with the help of practical examples. I hope that you will have understood types of bitwise operators in Java and practiced all example programs.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *