- Bitwise operators in java performs operation on bits
- Bitwise operators performs bit by bit operations
- Bit-wise operators operates on individual bits of operands.
Bit wise Operators in Java:
- ~ : Bit wise unary not
- & : Bit wise And
- | : Bit wise OR
- ^ : Bit wise Exclusive OR
1.Bit wise Unary Not ~:
- Bit wise Unary not Inverts the bits.
- Lets see a java program on bit wise unary not
Java Example program on bit wise unary not operator ~:
- package operatorsinjava;
- public class BitwiseUnaryNotDemo {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- int x=2;
- System.out.println(~x);
- int y= 3;
- System.out.println(~y);
- int z= 4;
- System.out.println(~z);
- }
- }
Output:
- -3
- -4
- -5
2. Bitwise AND operator:
- Bit wise And returns 1 if both operands position values are 1 otherwise 0.
- Bitwise operation on two numbers
- 1 & 2
- 001
010
-----
000 =0
----- - 2 & 3
- 010
011
-----
010 =2
-----
- package operatorsinjava;
- public class BitwiseAndDemo {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- int x=1;
- int y=2;
- System.out.println(x&y);
- int i=2;
- int j=3;
- System.out.println(i&j);
- System.out.println(4&5);
- }
- }
Output:
- 0
- 2
- 4
3.Bitwise OR operator in Java | :
- Bit wise OR returns 1 if any one operands position values are 1 or both 1 s. otherwise 0.
- 1 |2
- 001
010
-----
011 =3
----- - 2 | 3
- 010
011
-----
011 =3
-----
- package operatorsinjava;
- public class BitwiseORDemo {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- int x=1;
- int y=2;
- System.out.println(x|y);
- int i=2;
- int j=3;
- System.out.println(i|j);
- System.out.println(4|5);
- }
- }
Output:
- 3
- 3
- 5
4.Bit wise Exclusive OR operator in java ^:
- Bit wise XOR operator returns 1 if any of the operands bits position 1
- Java XOR operator returns 0 if both operands position is 1.
- Lest see java Xor on 1 ^ 2
- 1 ^ 2
- 001
010
-----
011 =3
----- - Lest see java xor operation on 2 ^3
- 2 ^ 3
- 010
011
-----
001 =1
-----
Java Example program on bitwise OR operator |:
- package operatorsinjava;
- public class BitwiseXORDemo {
- /**
- * @www.instanceofjava.com
- */
- public static void main(String[] args) {
- int x=1;
- int y=2;
- System.out.println(x^y);
- int i=2;
- int j=3;
- System.out.println(i^j);
- System.out.println(4^5);
- }
- }
Output:
- 3
- 1
- 1
Bagikan
Bitwise operators in java with example
4/
5
Oleh
Kris Kimcil