Bitwise Operators in Java
Bitwise Operators in Java
Bitwise operators are used to perform manipulation of individual bits of a number. They
can be used with any of the integral types (char, short, int, etc). They are used when
performing update and query operations of Binary indexed tree.
Bitwise OR (|) –
This operator is binary operator, denoted by ‘|’. It returns bit by bit OR of input
values, i.e, if either of the bits is 1, it gives 1, else it gives 0.
For example,
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)
~ 0101
________
1010 = 10 (In decimal)
Note – Compiler will give 2’s complement of that number, i.e., 2’s compliment of 10
will be -6.
// Java program to illustrate
// bitwise operators
public class operators {
public static void main(String[] args)
{
//Initial values
int a = 5;
int b = 7;
// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));
// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));
// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));
// bitwise and
// ~0101=1010
// will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a);
b >> 1 = 1
b >> 2 = (takes 2's compliment) = 1073741821
// Java program to illustrate
// shift operators
public class operators {
public static void main(String args[])
{
int a = 5;
int b = -10;