Month End Sale: Get Extra 10% OFF on Job-oriented Training! Offer Ending in
D
H
M
S
Get Now
What are Bitwise Operators in Java? Types, Examples and More

What are Bitwise Operators in Java? Types, Examples and More

20 Jun 2024
Beginner
1.48K Views
27 min read
Learn via Video Course & by Doing Hands-on Labs

Java Online Course Free with Certificate (2024)

Bitwise Operators in Java

Bitwise operators in Java are powerful tools for manipulating individual bits of data within primitive data types in Java.

In this Java tutorial, we'll learn about bitwise operators in Java with examples, types of Java Bitwise Operators, bitwise vs. logical operators in Java, and some practicals on Java Bitwise Operators.

If you haven't seen the tutorial, Operators in Java, go back and refer to it and come back. Without having a basic understanding of Java operators, you won't understand the Bitwise Operators in Java.

What is a Bitwise Operator in Java?

Bitwise Operators work on individual bits. They enable programmers to manipulate a value directly by working on its bits. Arithmetic operations like addition, subtraction, multiplication, etc., are done on bits in the backend.

Bitwise operators can be used to test whether an expression is true or false, toggle certain bits to clear bits, compare values of similar types, and shift right and left as needed.

They offer useful options for manipulating information stored in binary format, making them essential for critical operations in the Java programming language, ranging from basic calculations to complex memory operations.

Types of Bitwise Operators in Java

Types of Bitwise Operators in Java

Read More:

The seven bitwise operators in Java:

Bitwise OperatorDescription
&Bitwise AND
|Bitwise OR
^Bitwise Exclusive OR (XOR)
~Bitwise Complement
<<Bitwise Left Shift
>>Bitwise Right Shift
>>>Unsigned Right Shift Operator

1. Bitwise AND(&)

This operator performs & operation on each bit of the two operands. It essentially multiplies each bit by the corresponding bit in the other operand. The result is 1 if both the bits of the operand are 1; otherwise, 0 in all other cases.

The truth table of the Bitwise AND(&) operator for two operands, X and Y taking values; 0 and 1 is as follows:

XYX&Y
000
010
100
111

Example: Let’s perform bitwise & operation on 35 and 40

/* 35 = 00100011 (In Binary)
 40 = 00101000 (In Binary)

Bit Operation of 35 and 40
 00100011
& 00101000
 ________
 00100000 = 32 (In decimal) */

public class BitwiseANDExample {
    public static void main(String[] args) {
        int a = 35; // 00100011 in binary
        int b = 40; // 00101000 in binary
        int result = a & b; // 00100000 in binary (32 in decimal)
        System.out.println(a + " & " + b + " = " + result);
    }
}

The AND operator is commonly used for masking and clearing specific bits in a value.

Output

35 & 40 = 32

2. Bitwise OR(|)

The bitwise OR operator (|) compares each bit of two operands. If at least one of the bits is 1, the corresponding result bit is set to 1; otherwise, 0 in other cases.

The truth table of the Bitwise OR() operator for two operands, X and Y taking values; 0 and 1 is as follows:

XYX|Y
000
011
101
111

Example: Let’s perform bitwise | operation on 5 and 3

/* 5 = 00000101 (In Binary)
 3 = 00000011 (In Binary)

Bitwise OR Operation of 5 and 3
 00000101
| 00000011
 ________
 00000111 = 7 (In decimal) */

public class BitwiseORExample {
    public static void main(String[] args) {
        int a = 5; // binary: 0101
        int b = 3; // binary: 0011
        int result = a | b; // binary: 0111
        System.out.println(a + " | " + b + " = " + result); // Output: Result: 7
    }
}

The OR operator in the Java Compiler is often used for setting specific bits in a value.

Output

5 | 3 = 7

3. Bitwise XOR Operator(^)

The bitwise XOR operator (^) compares each bit of two operands. If the bits are different, the corresponding result bit is set to 1; otherwise, it is set to 0.

The truth table of the Bitwise XOR(^) operator for two operands, X and Y taking values; 0 and 1 is as follows:

XYX^Y
000
011
101
110

Example: Let’s perform bitwise ^ operation on 6 and 3

/* 6 = 00000110 (In Binary)
 3 = 00000011 (In Binary)

 Bitwise XOR Operation of 6 and 3
 00000110
^ 00000011
 ________
 00000101 = 5 (In decimal) */

public class BitwiseXORExample {
    public static void main(String[] args) {
        int num1 = 6; // binary representation: 0110
        int num2 = 3; // binary representation: 0011
        int result = num1 ^ num2; // bitwise exclusive OR operation
        System.out.println(num1 + " ^ " + num2 + " = " + result); // output: 6 ^ 3 = 5
    }
}

The XOR operator is useful for flipping bits or checking for differences between two values.

Output

6 ^ 3 = 5

4. Bitwise Complement(~)

It is a unary operator, working on only one operand. It changes 1s to 0s and 0s to 1s. It inverts all the bits of a number and changes the sign from positive to negative or vice versa.

X~X
01
10

As per the rule, the bitwise complement of any integer n is equal to - (n + 1). Let's understand this with an example.

Example: Let’s perform bitwise ~ operation on 60

/* 60 = 00111100 (In Binary)

 Bitwise complement Operation of 60
~ 00111100
 ________
  11000011 = 195 (In decimal) */ 

As per the rule, the bitwise complement of 60 should be -(60 + 1) = -61. In the above example, we can see that the complement of 60 is 11000011 which in decimal is 195. But, the binary result 11000011 is also equivalent to -61. To resolve this ambiguity, we will take the 2's complement of 11000011, i.e., the binary equivalent of -61. This will give the perfect output as -61.

2's Complement

2's complement of any number is calculated by adding 1 to the 1's complement of that number. This method gives a negative equivalent of any binary member.

// 2's complement of 61
61 = 00111101 (In Binary)

1's complement = 11000010

2's complement:
 11000010
    +   1
_________
 11000011

Here, we can see that the 2's complement of 61 is 11000011. This binary number is the complement of 60. Therefore, the bitwise complement of 60 is -(60 + 1) = -61.


import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
	int a = 60;  // binary: 00111100
      int result = ~a;  // binary: 11000011 (inverted)
     System.out.println(result);  // Output: -61 (in decimal)
}
}

Output

-61

5. Left Shift Operator(<<)

The left shift operator (<<) shifts the bits of the operand to the left by a specified number of positions. The vacant positions on the right are filled with zeros.

Left Shift Operator(<<)

Let's understand through an example in the Java Online Compiler.

Example

import java.util.Scanner;

public class BitwiseOperators {
public static void main(String[] args) {
	int a = 5;  // binary: 0101
      int result = a << 2;  // binary: 10100
      System.out.println(result);  // Output: 20
}
}

Left shifting is equivalent to multiplying the value by 2 raised to the power of the shift count.

Output

20

6. Right Shift Operator(>>)

The right shift operator (>>) shifts the bits of the operand to the right by a specified number of positions. The vacant positions on the left are filled based on the sign bit (arithmetic right shift for signed integers).

Example: Right Shift of a Positive Number

// right shift of 10
10 = 1010 (In Binary)

// perform 2-bit right shift
10 >> 2:
1010 >> 2 = 0010 (equivalent to 2)

As we performed the right shift on positive 10, there is no sign bit on the left. So, the leftmost bits are filled with 0s.

Example: Right Shift of a Negative Number

// right shift of -10
10 = 1010 (In Binary)

1's complement = 0101

2's complement:

 0101
  + 1
_______
 0110

Signed bit = 1

// perform 2-bit right shift
10 >> 2:
0110 >> 2 = 1101 (equivalent to -3)
import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
	int a = 20;  // binary: 10100
      int result = a >> 2;  // binary: 00101
      System.out.println(result);  // Output: 5
}
}    

Right shifting is equivalent to dividing the value by 2 raised to the power of the shift count.

Output

5

Read More - Java Certification Salary

7. Unsigned Right Shift Operator(>>>)

Here, the vacant leftmost position is filled with 0 instead of the sign bit.

Example: Unsigned Right Shift of 10 and -10

// unsigned right shift of 10
10 = 1010
10 >>> 2 = 0010

// unsigned right shift of -10
-10 = 0110 (see calculation above)
-10 >>> 2 = 1101

import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
	  int a = 10;
    int b = -10;
    
    System.out.println(a >>> 2);    
    System.out.println(b >>> 2);    
}
} 

Output

2
1073741821

Practical Use Cases and Benefits of Bitwise Operators in Java

1. Setting and Clearing Bits

Bitwise operators are commonly used to set and clear specific bits within a binary representation, especially when working with hardware registers or flags.

2. Optimizing Algorithms

Bitwise operations can be used to optimize certain algorithms, such as those related to graphics processing, compression, and encryption.

3. Bit Manipulation for Compact Storage

In scenarios where memory is a critical resource, bitwise operations can be employed to store multiple Boolean values in a single integer.

4. Network Programming

Bitwise operations are valuable in network programming for tasks like creating custom protocols and manipulating IP addresses.

5. Compression & Encryption

Huffman Coding (for compression) and Data Encryption Standard (for encryption)

Bitwise Operators in Java vs. Logical Operators in Java

While bitwise operators work with single bits, logical operators (&&, ||, !) work with Boolean expressions. Bitwise operators are better suitable for low-level bit manipulation, whereas logical operators are better suited for Boolean condition evaluation.
Bitwise OperatorsLogical Operators
The programming language offers the bitwise operator kind of operator to carry out calculations.An operator type offered by the programming language to carry out logic-based operations is known as a logical operator.
Bit-by-bit operations are carried out by bitwise operators, who operate on bits.A decision is made based on several conditions using logical operators.
Integer operands are used by bitwise operators. Expressions that produce a Boolean value are subject to the operations of logical operators.
These are utilized for bit manipulation tasks like bit checking, bit setting, and bit clearing.These are used to determine whether the expression complies with certain requirements.
Bitwise operations produce an integer value as their output.A Boolean value, which can either be true or false, is the outcome of logical operators.

Some Practice Problems on Bitwise Operators

1. Clear the nth bit of a number


public class ClearNthBit {
    public static void main(String[] args) {
        int number = 23; // Example number
        int n = 3; // Bit position to clear (0-indexed)

        System.out.println("Original number: " + number);
        System.out.println("Binary representation: " + Integer.toBinaryString(number));

        // Clear the nth bit
        int clearedNumber = clearBit(number, n);

        System.out.println("Number after clearing the " + n + "th bit: " + clearedNumber);
        System.out.println("Binary representation: " + Integer.toBinaryString(clearedNumber));
    }

    // Function to clear the nth bit of a number
    public static int clearBit(int number, int n) {
        // Create a mask with the nth bit set to 0 and all other bits set to 1
        int mask = ~(1 << n);

        // Apply the mask to clear the nth bit
        int result = number & mask;
        return result;
    }
}

In the above code:

  • The method clearBit() takes the number and the bit's position (0-indexed) to clear.
  • Inside the clearBit() method, we create a mask where the nth bit is set to 0 and all other bits are set to 1 using the bitwise NOT operator ~ and left shift <<.
  • We then apply the mask to the original number using the bitwise AND operator "&" to clear the nth bit.

Output

Original number: 23
Binary representation: 10111
Number after clearing the 3th bit: 23
Binary representation: 10111

2. Reverse bits of an integer


public class ReverseBits {
    public static void main(String[] args) {
        int num = 0x4; // Example number in hexadecimal
        System.out.println(revBits(num));
    }

    public static int revBits(int data) {
        int totalBits = Integer.SIZE; // Size of integer in bits
        int revNum = 0;

        for (int i = 0; i < totalBits; i++) {
            int temp = (data & (1 << i));
            if (temp != 0)
                revNum |= (1 << ((totalBits - 1) - i));
        }

        return revNum;
    }
}

In the main method in the above Java Online Editor, we have given the number 0x4 (in hexadecimal) and then called the revBits method to reverse its bits. The revBits method iterates over each bit of the input number, extracts it using the bitwise AND (&) operation, and sets the corresponding bit in the reversed number using the bitwise OR (|) operation.

Output

536870912

3. Swap two bits of a byte


public class SwapBits {
    public static void main(String[] args) {
        char data = 0xA; // Assigning hexadecimal value

        // Get 1st bit from data
        char bit_1 = (char) ((data >> 1) & 1);

        // Get 2nd bit from data
        char bit_2 = (char) ((data >> 2) & 1);

        // Get XOR of bit_1 and bit_2
        char xor_of_bit = (char) (bit_1 ^ bit_2);

        System.out.printf("After swapping the bits, data value is: %X\n", (data ^ (xor_of_bit << 1 | xor_of_bit << 2)));
    }
}
  • In the main method, we have initialized the hexadecimal value 0xA to the data variable.
  • We extract the 1st and 2nd bits of the data variable using bit manipulation operations.
  • After that, we compute the XOR of the 1st and 2nd bits.

Output

After swapping the bits, data value is: C
Explore More Operators:
  1. Assignment operator in Java
  2. Unary operator in Java
  3. Arithmetic operators in Java
  4. Relational operators in Java
  5. Logical operators in Java
  6. Ternary Operator in Java

Summary

After understanding the principles of bitwise operators in Java, it's time to master this complex concept. You'll get proficient with practice. Keep in mind that there is a connection between maths and computing below grammatical difficulties. Bitwise operators improve your coding abilities and set you apart from competing methods.

FAQs

Q1. What is Bitwise and logical AND in Java?

  • Bitwise AND (&): In C, bitwise AND is an operator that performs a bitwise AND operation on each pair of corresponding bits in two operands. The result is a new value where each bit is the result of the AND operation between the corresponding bits of the operands.
  • Logical AND (&&): Logical AND, on the other hand, is a boolean operator that evaluates two boolean expressions and returns true if both expressions are true. It short-circuits the evaluation, meaning that if the first expression is false, the second expression is not evaluated.

Q2. What is the difference between Bitwise and logical operators?

  • Bitwise Operators: Operate at the binary level, manipulating individual bits within data. They include AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
  • Logical Operators: Work on boolean expressions, evaluating conditions, and returning true or false. They include AND (&&), OR (||), and NOT (!). Logical operators short-circuit, meaning they may not evaluate the second operand if the result can be determined from the first operand.

Q3. What is the & symbol in bitwise?

In bitwise operations, the & symbol represents the AND operator. It performs a bitwise AND operation on each pair of corresponding bits in two operands. The result is a new value where each bit is the result of the AND operation between the corresponding bits of the operands.

Q4. What is the difference between OR and XOR?

  • OR (|) Operator: Performs a bitwise OR operation on each pair of corresponding bits in two operands. The result is 1 if at least one of the bits is 1.
  • XOR (^) Operator: Performs a bitwise exclusive OR operation on each pair of corresponding bits in two operands. The result is 1 if the bits are different; otherwise, the result is 0.

Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Software Architecture and Design Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Solution Architect Certification Training Jul 28 SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
Azure Developer Certification Training Jul 28 SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core Certification Training Jul 28 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
Data Structures and Algorithms Training with C# Jul 28 SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Microsoft Azure Cloud Architect Aug 11 SAT, SUN
Filling Fast
03:00PM to 05:00PM (IST)
Get Details
Angular Certification Course Aug 11 SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
ASP.NET Core Project Aug 24 SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this