Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Bitwise Operators



Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy −

Sr.No Operator & Description
1

&

This is the bitwise and operator

2

|

This is the bitwise or operator

3

^

This is the bitwise xor or Exclusive or operator

4

~

This is the bitwise negation operator

Here is the truth table showcasing these operators.

p q p & q p | q p ^ q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Example - Usage of Bitwise AND and OR operator

In this example, we're creating two variables x and y and using bitwise operators. We've performed bitwise AND and bitwise OR operations and printed the results.

Example.groovy

class Example { 
   static void main(String[] args) { 
      int x = 60;	/* 60 = 0011 1100 */
      int y = 13;	/* 13 = 0000 1101 */
      int z = 0;

      z = x & y;        /* 12 = 0000 1100 */
      println("x & y = " + z );

      z = x | y;        /* 61 = 0011 1101 */
      println("x | y = " + z );
   } 
}

Output

When we run the above program, we will get the following result.

x & y = 12
x | y = 61

Example - Usage of Bitwise AND and OR operator

In this example, we're creating two variables x and y and using bitwise operators. We've performed bitwise XOR and complement operations and printed the results.

Example.groovy

class Example { 
   static void main(String[] args) { 
      int x = 60;	/* 60 = 0011 1100 */
      int y = 13;	/* 13 = 0000 1101 */
      int z = 0;

      z = x ^ y;        /* 12 = 0000 1100 */
      println("x ^ y = " + z );

      z = ~x ;        /* 61 = 0011 1101 */
      println("~x = " + z );
   } 
}

Output

When we run the above program, we will get the following result.

x ^ y = 49
~x = -61

Example - Usage of Bitwise Shift operator

In this example, we're creating two variables x and y and using bitwise operators. We've performed left shift, right shift and zero fill right shift operations and printed the results.

Example.groovy

class Example { 
   static void main(String[] args) { 
      int x = 60;	/* 60 = 0011 1100 */
      int y = 0;	

      y = x << 2;       /* 240 = 1111 0000 */
      println("x << 2 = " + y );

      y = x >> 2;       /* 15 = 1111 */
      println("x >> 2  = " + y );

      y = x >>> 2;      /* 15 = 0000 1111 */
      println("x >>> 2 = " + y );
   } 
}

Output

When we run the above program, we will get the following result.

x << 2 = 240
x >> 2  = 15
x >>> 2 = 15
Advertisements