Let’s learn bitwise operators in java.

## Bitwise operators in java

Bitwise operator works on integer data bit by bit individually. These integer data comprises of byte, short, int and long types.

Here are types of bitwise operators,

- Bitwise AND (&)
- Bitwise inclusive OR (|)
- Bitwise exclusive OR (^)
- Bitwise Compliment (~)

**Bitwise AND (&):** bitwise AND operator returns 1 only if both bits are 1, else returns 0. It is a binary operator denoted by the symbol ampersand (&).

a | b | a & b |

0 | 0 | 0 |

0 | 1 | 0 |

1 | 0 | 0 |

1 | 1 | 1 |

Let’s see an example on bitwise AND (&) operator.

public class BitwiseAndOperatorExample { public static void main(String[] args) { int a = 7, b = 6; System.out.println("a & b = " + (a & b)); } }

**Output:**

a & b = 6

**Bitwise inclusive OR (|):** bitwise inclusive OR operator returns 1 only if either of the bit is 1, else returns 0. It is a binay operator denoted by the symbol pipe (|).

a | b | a | b |

0 | 0 | 0 |

0 | 1 | 1 |

1 | 0 | 1 |

1 | 1 | 1 |

Let’s see an example on bitwise inclusive OR (|) operator.

public class BitwiseInclusiveOrOperatorExample { public static void main(String[] args) { int a = 7, b = 6; System.out.println("a | b = " + (a | b)); } }

**Output:**

a | b = 7

**Bitwise exclusive OR (^):** bitwise exclusive OR operator returns 0 only if both bits are same, else returns 1. It is a binary operator denoted by the symbol caret (^).

a | b | a ^ b |

0 | 0 | 0 |

0 | 1 | 1 |

1 | 0 | 1 |

1 | 1 | 0 |

Let’s see an example on bitwise exclusive OR (^) operator.

public class BitwiseExclusiveOrOperatorExample { public static void main(String[] args) { int a = 7, b = 6; System.out.println("a ^ b = " + (a ^ b)); } }

**Output:**

a ^ b = 1

**Bitwise Compliment (~):** bitwise compliment operator returns complement of a bit. That is, this operator makes every 0 to 1 and vice versa. It is an unary operator denoted by the symbol tilde (~).

a | ~a |

0 | 1 |

1 | 0 |

Let’s see an example on bitwise compliment (~) operator.

public class BitwiseComplimentOperatorExample { public static void main(String[] args) { int a = 7; System.out.println("~a = " + (~a)); } }

**Output:**

~a = -8

Also read – shift operator in java