Site icon TestingDocs.com

Java Bitwise Operators

Overview

In this tutorial, we will learn about Java Bitwise Operators. Bitwise logical operators perform on the individual bits (0 and 1 )of their operands.

Bitwise Operators

Java has a number of operators for working with the individual bits within a value.
The table lists the bitwise operators:

 

Operator Description
&                The Bitwise AND. Bitwise AND operator produces 1 if the bits in both the operands are 1; otherwise, it produces zero
| The Bitwise OR. Bitwise OR operator produces 1 if one or both of the bits in its operands are 1, and produces 0 if both of the corresponding bits are 0
^ The Bitwise Exclusive OR(XOR). The XOR operator produces 1 where the bits in its operands are different and produces 0 if they are the same
~

 

Bitwise complement. Bitwise complement operator flips the bits of the operand i.e. what was a 1 bit will now be 0, and vice versa.

Code Example

The code listing is the example of the bitwise logical operators, such as |,^, and &.

/* 
 * Java Program to demonstrate 
 * Bitwise Logical Operators.
 * Java Tutorials -- www.TestingDocs.com 
 */
public class BitwiseOperatorExample
{
    public static void main(String args[])
     {
    	  //Declare two variables
          int x =3;
          int y =6;
          System.out.println("x=: " + x);
          System.out.println("y=: " + y);
          // Bitwise AND operation
          System.out.println("x&y is:= " + (x & y));
          // Bitwise OR operation
          System.out.println("x|y is:= " + (x | y)); 
          // Bitwise XOR operation
          System.out.println("x^y is:= " + (x ^ y));
      }
}

Program Output

x=: 3
y=: 6
x&y is:= 2
x|y is:= 7
x^y is:= 5

 

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version