Java: Bitwise Operator

Although not a commonly used operator, in the java programming language the bitwise operator is essential to keep in mind that this operator handles the operand inside the variable as its 32-bit machine language. Although it's operating under binary digits, the output is displayed in decimal.

1. Bitwise AND (&)

Bitwise AND and && from the logical operator are two separate things that cannot be confused with one another. Here the operator gives out 1 if both the operand bits are 1. Else, it gives out 0.

So basically.

0 and 0 is equal to 0
0 and 1 is equal to 0
1 and 0 is equal to 0
1 and 1 is equal to 1

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 26, val3, val4 = 10, val5;
        val5 = val1 & val2;
        System.out.println(val5);
    }
}

Output: 10

00001111
00011010
--------
00001010 => 10
  • The binary value of 15 is 00001111 and 26 is 00011010.
  • So 00001010 is 10 in decimal. Turns out the final output, as discussed, has given out the decimal value.

2. Bitwise OR (|)

If either of both sides of an operand consists of 1, the bit gives out 1. Else it gives out 0.

0 and 0 is equal to 0
0 and 1 is equal to 1
1 and 0 is equal to 1
1 and 1 is equal to 1

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 26, val3, val4 = 10, val5;
        val5 = val1 | val2;

        System.out.println(val5);
    }
}

Output: 31

00001111
00011010
--------
00011111  => 31

3. Bitwise XOR (^)

This one gives out 0 if both operand's bits are the same and gives out 1 if it is different.

0 and 0 is equal to 0
0 and 1 is equal to 1
1 and 0 is equal to 1
1 and 1 is equal to 0

Example 

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 26, val3, val4 = 10, val5;
        val5 = val1 ^ val2;
        System.out.println(val5);
    }
}

Output: 21

00001111
00011010
--------
00010101  => 21

4. Bitwise Complement (~)

The Complement Operator inverts the operand bits opposite to its corresponding bit.

00001111 in Complement turns to 11110000

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 26, val3, val4 = 10, val5;
        val5 = ~val1;
        
        System.out.println(val5);
    }
}

Output: -16

While converting 00001111 to 11110000, it gives out 240. The value is then computed to decimal signed 2's complement. 2's complement is nothing, but after the inversion, it gets added with 1.

11110000
       1
---------
11110001 => -16
Thu, 10/21/2021 - 11:23

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags