Bitwise logical operators in java Bitwise operators is used to control values of primitive data-types such as long, integer, short and byte. These operators do changes to the variables by doing some action and manipulation on bits level. There are four defined bitwise operators in java which are : AND operator, OR operator, XOR operator and complement operator. The first three operators are binary which means that they need two operands while the last one is unary operator which means it needs only one operand. Next will explain the usage of each operator by example.
1- The AND operator : (&) The AND(&) logical operator gives one (1) in only case one case where the two inputs
Code:
x y x&y ----------------------------- 0 0 0 0 1 0 1 0 0 1 1 1
Example using & operator on bytes java code
byte x = 50; byte y = 51; byte result = (byte) (x&y); System.out.println("Result of x&y= : " + result );
The result equal = 50 which is in binary:
Code:
00110010 00110011 ------------- 00110010
& operator on Integers: java code
int xInt = 30; int yInt = 31; int result = (xInt&yInt); System.out.println("Result of x&y (Integers)= : " + result );
The output is :
Code:
Result of x&y (Integers)= : 30
2- The OR operator : (|) The OR operators gives one(1) if any of the two inputs equals one, zero otherwise.
Code:
x y x|y ----------------------------- 0 0 0 0 1 1 1 0 1 1 1 1
Example on |(OR) operator on bytes
java code
byte x = 50; byte y = 51; byte result = (byte) (x|y); System.out.println("Result of x|y= : " + result );
The output is :
Code:
The result equal = 51
Code:
00110010 00110011 ------------- 00110011
Example on |(OR) operator on integers java code
int xInt = 30; int zInt=33; int result = (xInt|zInt); System.out.println("Result of x|y (Integers)= : " + result );
The output is :
Code:
Result of x|y (Integers)= : 63
3- The XOR operator : (^) The XOR(^) operator gives one(1) if the inputs are different, otherwise zero.
Code:
x y x^y ----------------------------- 0 0 0 0 1 1 1 0 1 1 1 0
Example on ^ operator on bytes
java code
byte x = 50; byte y = 51; byte result = (byte) (x^y); System.out.println("Result of x^y= : " + result );
The result equal = 1
Code:
00110010 00110011 ------------- 00000001
Example on ^ operator on Integers java code
int xInt = 30; int zInt=31; int result = (xInt^zInt); System.out.println("Result of x^y (Integers)= : " + result );
The output is :
Code:
Result of x^y (Integers)= : 1
4- The Inversion Operator: (~) Invert each bit in the byte (one's complement of bits array).
Example :
Code:
~00110010 = 11001101
Invert operator on integer java code
int xInt = 30; int result = ~xInt; System.out.println("Result of ~xInt(Integers)= : " + result );
The output is :
Code:
Result of ~xInt(Integers)= : -31
Boolean Inversion Operator (!) invert the value of boolean variable
_________________ Please recommend / share my post if you found it helpful.