Bitwise operators in Java Programming

Bitwise operators in Java Programming

Previous Home Next

 

 Java defines several Bitwise operations, which can be applied to the integer types, long, int, short, char, and byte.
 These operators act upon the individual bits of their operand.
  The Java programming language also provides operators that perform bitwise and bit shift operations on integral types.


Java's bitwise operators operate on individual bits of integer (int and long) values. 
If an operand is shorter than an int, it is promoted to int before doing the operations.

The unary bitwise complement operator "~"

inverts a bit pattern:
it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0".
For example, a byte contains 8 bits:
applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".


The signed left shift operator "<<" shifts a bit pattern to the left,
and the signed right shift operator ">>" shifts a bit pattern to the right.

The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand.
The unsigned right shift operator ">>>" shifts a zero into the leftmost position,
while the leftmost position after ">>" depends on sign extension.

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation
 


 
byte x = 30;
byte y = 31;
byte result = (byte) (x^y);
System.out.println("Result of x^y= : " + result );


Previous Home Next