0
2.2kviews
Explain Bitwise operators available in JAVA with example.

Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology

Marks: 5 M

Year: May 2014

1 Answer
0
5views
  • Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte. These operators act upon the individual bits of their operands.
  • They are summarized in the following table:
Operator Result
~ Bitwise unary NOT
& Bitwise AND
Bitwise OR
^ Bitwise exclusive oR
$\gt\gt$ Shift right
$\gt\gt\gt$ Shift right zero fill
$\lt\lt$ Shift left
&= Bitwise AND assignment
= Bitwise OR assignment
^= Bitwise exclusive OR assignment
$\gt\gt=$ Shift right assignment
$\gt\gt\gt=$ Shift right zero fill assignment
$\lt\lt=$ Shift left assignment
  • Bitwise operators manipulate the bits within an integer. All of the integer types are represented by binary numbers of varying bit widths.
  • Assume if a = 60; and b = 13; now in binary format they will be as follows:

a = 0011 1100

b = 0000 1101

  • Let’s have a detailed look at operations:
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both operands. (A & B) will give 12 which is 0000 1100
Binary OR Operator copies a bit if it exists in either operand. (A B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (A ^ B) will give 49 which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
<< Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. A << 2 will give 240 which is 1111 0000
$\gt\gt$ Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. A >> 2 will give 15 which is 1111
$\gt\gt\gt$ Shift right zero fill operators. 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. A >>>2 will give 15 which is 0000 1111
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false.
Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.
Please log in to add an answer.