What is a Bitwise Operator in Java? Type, Example and More
Java Programming For Beginners Free Course
Bitwise Operators in Java: An Overview
Bitwise operators in Java are powerful tools that allow you to manipulate individual bits of data within primitive data types. Java tutorial will help you a lot if you're interested in mastering the bitwise operators in Java. Previously we learned about different types of operators briefly. In this article on bitwise operators, we will take an in-depth look at what bitwise operators are, their syntax, and types; when they should be used, and some practical implementations.
What is a Bitwise Operator in Java?
Bitwise operators in Java allow you to control individual bits of data within integer types. These operators provide binary-level operations, allowing developers to work with the underlying binary data representation. Understanding bitwise operators is essential for low-level data manipulation activities like cryptography, image processing, and network programming.
Explore More Operators:
- Assignment operator in Java
- Unary operator in Java
- Arithmetic operators in Java
- Relational operators in Java
- Logical operators in Java
- Ternary Operator in Java
Syntax:
operand1 binary_operator operand2
Types of Bitwise Operators in Java
Read More - Java 50 Interview Questions
The truth table of Bitwise Operator in Java:
Operators | Symbol | Uses |
Bitwise AND | & | num1 & num2 |
Bitwise Exclusive OR (XOR) | ^ | num1 ^ num2 |
Bitwise Inclusive OR | \ | |
Bitwise Complement | ~ | ~ num |
Bitwise Left Shift | << | num1 << num2 |
Bitwise Right Shift | >> | num1 >> num2 |
Unsigned Right Shift Operator | >>> | num1>>>num2 |
1. AND Operator (&)
Example:
import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // binary: 0001
System.out.println(result); // Output: 1
}
}
The AND operator is commonly used for masking and clearing specific bits in a value.
Output
1
2. OR Operator (|)
Example:
import java.util.Scanner;
public class BitwiseOperators {
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(result);
}
}
The OR operator in the Java Compiler is often used for setting specific bits in a value.
Output
7
3. XOR Operator (^)
Example:
import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a ^ b; // binary: 0110
System.out.println(result); // Output: 6
}
}
The XOR operator is useful for flipping bits or checking for differences between two values.
Output
6
4. NOT Operator (~)
Example:
import java.util.Scanner;
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // binary: 0101
int result = ~a; // binary: 1010 (inverted)
System.out.println(result); // Output: -6 (in decimal)
}
}
The NOT operator is often used for creating the two's complement of a binary number, and it can also be used for bitwise negation.
Output
-6
5. Left Shift Operator (<<)
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 (>>)
Example:
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
Practical Use Cases and Benefits of Bitwise Operators in Java
1. Setting and Clearing Bits:
- Bitwise operators are commonly used for setting and clearing 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
Bitwise Operators | Logical 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 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 number
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
Summary
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?
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.