Java Bitwise Operators Compound Assignments

Introduction

Java binary bitwise operators have a compound form.

It combines the assignment with the bitwise operation.

For example, the following two statements, which shift the value in a right by four bits, are equivalent:

int a = 32;
a = a >> 4;  
a >>= 4; 

The following two statements are equivalent:

a = a | b;  
a |= b; 

The following program uses compound bitwise operator assignments to manipulate the variables:

public class Main {
  public static void main(String args[]) {
    int a = 1;// w w  w .ja va 2  s .  com
    int b = 2;
    int c = 3;

    a |= 4;
    b >>= 1;
    c <<= 1;
    a ^= c;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
  }
}



PreviousNext

Related