Bitwise operator use AND/OR to determine the result on bit by bit basis.
3 Bitwise operator are :
& (Bitwise AND)
| (Bitwise Inclusive OR)
^(Bitwise exclusive OR)
1. Bitwise & (AND) operator :
The & operator combine corresponding bit between two numbers and if both bits are 1 then only resultant bit is 1.If either one of the bit is 0, then resultant bit is 0.
Example :
int x=7;
int z=2;
the result of x & z will be 2 .
Explanation – if both bits are 1 then only corresponding result is 1 else it is 0 as shown below :
7 -> 0111
2 -> 0010
2 -> 0010
x & z result is 2.
Program :
class BitwiseAndDemo { public static void main(String[] args) { int x=7; int z=2; int result= x&z; System.out.println("result is :"+result); } }
output – result is :2
2.Bitwise |(inclusive OR) operator :
Inclusive OR ( I ) operator set result bit to 1 if either one of them is 1, it will result 0 only if both bit are 0.
x=6
z=1
6 -> 0110
1 -> 0001
7 -> 0111
x | z result is 7
Program :
class BitwiseOrDemo { public static void main(String[] args) { int x=6; int z=1; int result= x | z; System.out.println("Inclusive OR result is :"+result); } }
Output – Inclusive OR result is :7
3.Bitwise ^(exclusive OR) operator
The ^ operator compare two bits and check whether these bits are different .If they are different, result is 1 otherwise result is 0.This operator is known as XOR operator.
Example :
int x=5;
int y=9;
x^y is 12.
5 –> 0101
9 –> 1001
12 –> 1100
class ExOrDemo { public static void main(String[] args) { int x=5; int z=9; int result= x ^ z; System.out.println("Exclusive OR result is :"+result); } }
Output – Exclusive OR result is :12
Here are 10 interview programs that demonstrate the use of Java bitwise operators, along with explanations:
- Program: Counting Set Bits
public class CountSetBits { public static int countSetBits(int num) { int count = 0; while (num > 0) { count += num & 1; num >>= 1; } return count; } public static void main(String[] args) { int number = 25; // Binary: 00011001 int result = countSetBits(number); System.out.println("Number of set bits: " + result); // Output: Number of set bits: 3 } }
Explanation: The program counts the number of set bits (bits with a value of 1) in a given number. It uses the bitwise AND operator (&
) with 1
to check if the least significant bit is set. If it is, the count is incremented. The number is then right-shifted (>>=
) to check the next bit, and the process continues until all bits have been examined.
- Program: Swap Two Numbers
public class SwapNumbers { public static void swapNumbers(int a, int b) { a = a ^ b; b = a ^ b; a = a ^ b; System.out.println("After swapping - a: " + a + ", b: " + b); } public static void main(String[] args) { int num1 = 10; int num2 = 20; System.out.println("Before swapping - num1: " + num1 + ", num2: " + num2); swapNumbers(num1, num2); // Output: After swapping - a: 20, b: 10 } }
Explanation: The program swaps the values of two numbers without using a temporary variable. It uses the XOR operator (^
) to perform the bitwise XOR operation on the numbers. By applying XOR operations in sequence, the original values of the numbers are swapped.
- Program: Check Power of Two
public class PowerOfTwo { public static boolean isPowerOfTwo(int num) { return (num > 0) && ((num & (num - 1)) == 0); } public static void main(String[] args) { int number1 = 16; // Power of 2 (2^4) int number2 = 15; // Not a power of 2 System.out.println(number1 + " is a power of two: " + isPowerOfTwo(number1)); // Output: 16 is a power of two: true System.out.println(number2 + " is a power of two: " + isPowerOfTwo(number2)); // Output: 15 is a power of two: false } }
Explanation: The program checks if a given number is a power of two. It uses the fact that powers of two have only a single bit set. By performing the bitwise AND operation of num
and num - 1
, if the result is 0
and num
is greater than 0
, it indicates that num
is a power of two.
- Program: Find Maximum of Two Numbers
public class MaximumOfTwoNumbers { public static int findMaximum(int a, int b) { int diff = a - b; int sign = (diff >> 31) & 1; return a - (sign * diff); } public static void main(String[] args) { int number1 = 10; int number2 = 20; System.out.println("Maximum of " + number1 + " and " + number2 + ": " + findMaximum(number1, number2)); // Output: Maximum of 10 and 20: 20 } }
Explanation: The program finds the maximum of two numbers without using any conditional statements. It calculates the difference between the numbers and determines the sign of the difference using the bitwise right shift operator (>>
) with 31
. It then performs a bitwise AND operation (&
) with 1
to extract the sign bit. The maximum value is calculated by subtracting the appropriate value based on the sign.
- Program: Toggle Case of Characters
public class ToggleCase { public static String toggleCase(String str) { char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { chars[i] ^= 32; } return new String(chars); } public static void main(String[] args) { String text = "Hello, World!"; System.out.println("Original: " + text); System.out.println("Toggled Case: " + toggleCase(text)); // Output: hELLO, wORLD! } }
Explanation: The program toggles the case of characters in a given string. It uses the XOR operator (^
) with 32
to toggle the case. The ASCII values of lowercase and uppercase letters differ by 32
, so performing the XOR operation with 32
flips the case of the characters.
- Program: Check Even or Odd
public class EvenOddCheck { public static boolean isEven(int num) { return (num & 1) == 0; } public static void main(String[] args) { int number = 15; System.out.println(number + " is even: " + isEven(number)); // Output: 15 is even: false } }
Explanation: The program checks if a given number is even or odd using bitwise AND operation with 1
. If the result is 0
, it indicates an even number since even numbers have their least significant bit set to 0
.
- Program: Multiply by Two
public class MultiplyByTwo { public static int multiplyByTwo(int num) { return num << 1; } public static void main(String[] args) { int number = 5; System.out.println("Result: " + multiplyByTwo(number));// Output: Result: 10 } }
Explanation: The program multiplies a given number by two using the left shift operator (<<
). Shifting the bits to the left by 1
position is equivalent to multiplying the number by 2
.
- Program: Divide by Two
public class DivideByTwo { public static int divideByTwo(int num) { return num >> 1; } public static void main(String[] args) { int number = 10; System.out.println("Result: " + divideByTwo(number)); // Output: Result: 5 } }
Explanation: The program divides a given number by two using the right shift operator (>>
). Shifting the bits to the right by 1
position is equivalent to dividing the number by 2
.
- Program: Check Palindrome Number
public class PalindromeCheck { public static boolean isPalindrome(int num) { int reversed = 0; int original = num; while (num > 0 ) { reversed = (reversed << 1) | (num & 1); num >>= 1; } return reversed == original; } public static void main(String[] args) { int number = 9; System.out.println(number + " is a palindrome: " + isPalindrome(number)); // Output: 9 is a palindrome: true } }
Explanation: The program checks if a given number is a palindrome using bitwise operations. It reverses the binary representation of the number using the left shift operator (<<
) and bitwise OR (|
). By comparing the reversed number with the original number, it determines if they are equal, indicating a palindrome.
- Program: Check Power of Four
public class PowerOfFourCheck { public static boolean isPowerOfFour(int num) { return (num & (num - 1)) == 0 && (num & 0x55555555) != 0; } public static void main(String[] args) { int number1 = 16; // Power of 4 (4^2) int number2 = 15; // Not a power of 4 System.out.println(number1 + " is a power of four: " + isPowerOfFour(number1)); // Output: 16 is a power of four: true System.out.println(number2 + " is a power of four: " + isPowerOfFour(number2)); // Output: 15 is a power of four: false } }
Explanation: The program checks if a given number is a power of four. It first checks if the number is a power of two using the bitwise AND operation with num
and num - 1
. It then performs a bitwise AND operation with num
and 0x55555555
(a hexadecimal representation of the pattern 1010101010101010101010101010101
). If both conditions are satisfied, it indicates that the number is a power of four.
These programs demonstrate the usage of Java bitwise operators in various scenarios. They showcase how bitwise operators can be leveraged to perform operations such as counting set bits, swapping numbers, checking powers of two/four, toggling case, and more. Understanding and utilizing bitwise operators effectively can be valuable in certain programming scenarios that require low-level bit manipulation or optimization.
Happy Reading..