Java Bitwise Operators

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. java 2  s  . com*/
    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:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures