Java Programming Tutorial Index

Java Fundamentals

The Java Bitwise Operators allow access and modification of a particular bit inside a section of the data. It can be applied to integer types and bytes, and cannot be applied to float and double.



Operator Meaning Work
& Binary AND Operator There are two types of AND operators in Java: the logical && and the binary &. Binary & operator work very much the same as logical && operators works, except it works with two bits instead of two expressions. The "Binary AND operator" returns 1 if both operands are equal to 1.
| Binary OR Operator Like "AND operators ", Java has two different "OR" operators: the logical || and the binary |. Binary | Operator work similar to logical || operators works, except it, works with two bits instead of two expressions. The "Binary OR operator" returns 1 if one of its operands evaluates as 1. if either or both operands evaluate to 1, the result is 1.
^ Binary XOR Operator It stands for "exclusive OR" and means "one or the other", but not both. The "Binary XOR operator" returns 1 if and only if exactly one of its operands is 1. If both operands are 1, or both are 0, then the result is 0.
~ Binary Complement Operator
<< Binary Left Shift Operator
>> Binary Right Shift Operator
>>> Shift right zero fill operator

Program to Show Bitwise Operators Works

Example:

public class bitwiseop {
 public static void main(String[] args) {
  //Variables Definition and Initialization
  int num1 = 30, num2 = 6, num3 =0;

  //Bitwise AND
  System.out.println("num1 & num2 = " + (num1 & num2));
  
  //Bitwise OR
  System.out.println("num1 | num2 = " + (num1 | num2) );
  
  //Bitwise XOR
  System.out.println("num1 ^ num2 = " + (num1 ^ num2) );
  
  //Binary Complement Operator
  System.out.println("~num1 = " + ~num1 );

  //Binary Left Shift Operator
  num3 = num1 <<  2;
  System.out.println("num1 << 1 = " + num3 );

  //Binary Right Shift Operator
  num3 = num1 >>  2;
  System.out.println("num1 >> 1  = " + num3 );

  //Shift right zero fill operator
  num3 = num1 >>> 2;
  System.out.println("num1 >>> 1 = " + num3 );
  
 }
}

Output:

num1 & num2 = 6
num1 | num2 = 30
num1 ^ num2 = 24
~num1 = -31
num1 << 1 = 120
num1 >> 1  = 7
num1 >>> 1 = 7


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram