Java Bitwise operators work on bits and perform bit-by-bit operations. These operators can be applied to the integer types, long, int, short, char, and byte. There are a lot of bitwise operators supported in Java.

Let's take an example to demonstrate bitwise operators in Java language. Suppose if a = 60 and b = 13; now in binary format they will be as follows -

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

A list of bitwise operators in Java language:

S.No. | Operators | Example | Description |
---|---|---|---|

1. | & (Bitwise AND) | (a & b) will give 12 which is 0000 1100 | The Bitwise AND operator copies a bit to the result if it exists in both operands. |

2. | | (Bitwise OR) | (a | b) will give 61 which is 0011 1101 | The Bitwise OR operator copies a bit to the result if it exists in any of the two operand. |

3. | ^ (Bitwise XOR) | (a ^ b) will give 49 which is 0011 0001 | The Bitwise XOR operator copies the bit if it is set in one operand but not in both. |

4. | ~ (Bitwise Compliment) | (~a ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number. | The Bitwise ones complement operator is unary and used to flip bits. |

5. | << (left shift) | a << 2 will give 240 which is 1111 0000 | The Bitwise left shift operator specifies that the left operands value is moved left by the number of bits specified by the right operand. |

6. | >> (right shift) | a >> 2 will give 15 which is 1111 | The Bitwise right shift operator specifies that the left operands value is moved right by the number of bits specified by the right operand. |

8. | >>> (zero fill right shift) | a >>>2 will give 15 which is 0000 1111 | The Bitwise shift right zero fill operator specifies that the left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros. |

The following program is a simple example that demonstrates the Bitwise operators.

/** * * @author JavaTportal Corporation * */ public class BitwiseOperatorsExample { public static void main(String args[]) { int a = 60; /* 60 = 0011 1100 */ int b = 13; /* 13 = 0000 1101 */ int c = 0; c = a & b; /* 12 = 0000 1100 */ System.out.println("a & b = " + c ); c = a | b; /* 61 = 0011 1101 */ System.out.println("a | b = " + c ); c = a ^ b; /* 49 = 0011 0001 */ System.out.println("a ^ b = " + c ); c = ~a; /*-61 = 1100 0011 */ System.out.println("~a = " + c ); c = a << 2; /* 240 = 1111 0000 */ System.out.println("a << 2 = " + c ); c = a >> 2; /* 15 = 1111 */ System.out.println("a >> 2 = " + c ); c = a >>> 2; /* 15 = 0000 1111 */ System.out.println("a >>> 2 = " + c ); } }

a & b = 12 a | b = 61 a ^ b = 49 ~a = -61 a << 2 = 240 a >> 2 = 15 a >>> 2 = 15

Next Concept
Logical Operators