Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » OperatorsRSS Feeds

Bitwise Operators

Posted By: Reggie Fischer     Category: Java     Views: 60981

This article lists and explains bitwise operators available in java.

Bitwise operators can be used for variables of type char, byte, short, int and long. If we use different type of integers like int and long, the result will be of wider type. Operations on byte and short types may give unexpected results since operands are promoted to integers during intermediate operations. 

There are basically three categories of bitwise operators : logical, shift and assignment.

Bitwise Operators

 Operators

Meaning  

 ~varName

Compliment - Change all zeros to ones and ones to zeros. 

 var1 & var2

And - And each bit of var1 with corresponding bit in var2. 

 var1 | var2 

OR - Or each bit of var1 with corresponding bit in var2.  

 var1 ^ var2

XOR - XOR each bit of var1 with corresponding bit in var2.  

 var1 << var2

Shift left - Shift x to the left by y bits. High order bits lost. Zero bits fill in right bits. 

 var1 >> var2

Shift right signed - Shift x to the right by y bits. Low order bits lost. Same bit value as sign (0 for positive numbers, 1 for negative) fills in the left bits. 

 var1 >>> var2

Shift right unsigned - Shift x to the right by y bits. Low order bits lost. Zeros fill in left bits regardless of sign. 



Example of Bitwise Operators

Example 1 : Program that displays use of bitwise operators i.e ~, &, |, ^, <<, >>, >>>

class BitwiseOptrDemo 
{
   public static void main(String args[]) 
   {
int x = 0xAAAA; 
int y = 0x9999; 
System.out.println("x & y : " + (x & y));
System.out.println("x | y : " + (x | y));
System.out.println("x ^ y : " + (x ^ y));
System.out.println("~x : " + (~x));
System.out.println("x << y : " + (x << y));
System.out.println("x >> y : " + (x >> y));
System.out.println("x >>> y : " + (x >>> y));
   }
  
Share: 

 
 

Didn't find what you were looking for? Find more on Bitwise Operators Or get search suggestion and latest updates.

Reggie Fischer
Reggie Fischer author of Bitwise Operators is from Frankfurt, Germany.
 
View All Articles

 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
Hemlata Bansal from Australia Comment on: Jul 23
Where are the answers

View All Comments