Java Bitwise Operators

In this chapter you will learn:

  1. What are bitwise operation
  2. Bitwise operators List
  3. How to use bitwise operator assignments

Description

Bitwise Operators act upon the individual bits of their operands. Java bitwise operators can be applied to the integer types: long, int, short, char, byte.

Bitwise operators List

The following table lists all Java bitwise operators.

Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment

Example

Bitwise operator assignments combines the assignment with the bitwise operation. The following two statements are equivalent:


a = a >> 4; 
a >>= 4;  

The following two statements are equivalent:


a = a | b; 
a |= b;

The following program demonstrates the bitwise operator assignments:

 
public class Main {
  public static void main(String args[]) {
    int a = 1;/* w w w. jav  a 2 s .  co m*/
    int b = 2;
    int c = 3;
    a |= 2;
    b >>= 2;
    c <<= 2;
    a ^= c;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);

  }
}

The output of this program is shown here:

Next chapter...

What you will learn in the next chapter:

  1. What is Left Shift Operator
  2. Syntax for Left Shift Operator
  3. Example - Left Shift Operator
  4. Example - double the original value
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator