Back to Java
2026-04-017 min read

List of Java Bitwise Operators

Learn List of Java Bitwise Operators step by step with clear examples and exercises.

Title: Java Bitwise Operators - A full guide for Coders

Why This Matters

In programming, understanding bitwise operators is crucial for performing low-level operations, optimizing code, and solving complex problems efficiently. These operators manipulate individual bits of data rather than treating them as whole numbers, which can be particularly useful in situations involving binary data or when dealing with memory management. In Java, bitwise operators play a significant role in interviews, coding challenges, and real-world programming scenarios.

The Importance of Bitwise Operators

Bitwise operators allow developers to perform operations on individual bits of a number rather than the whole value. This can lead to more efficient code, especially when dealing with binary data or memory management tasks. Understanding bitwise operators is essential for mastering low-level programming and solving complex problems efficiently.

Prerequisites

Before diving into the world of Java bitwise operators, it is essential to have a solid understanding of the following concepts:

  1. Basic Java syntax and data types
  2. Variables and their storage in memory
  3. Arithmetic and logical operators
  4. Control structures (if-else, loops)
  5. Understanding binary numbers and their conversion to decimal
  6. Familiarity with hexadecimal and octal number systems
  7. Knowledge of basic memory management concepts
  8. Understand the difference between bitwise operators and logical operators in Java
  9. Be comfortable working with integers, both positive and negative

Core Concept

Definition of Bitwise Operators

Bitwise operators perform operations on individual bits of a number rather than the whole value. These operators compare or modify the binary representation of numbers. In Java, there are six bitwise operators: &, |, ^, ~, <<, and >>.

Bitwise AND (&)

The bitwise AND operator compares each corresponding bit in two numbers and sets the result bit to 1 only if both input bits are 1. In Java, it is represented as &.

int a = 60; // binary: 0011 1100
int b = 13; // binary: 0000 1101
int result = a & b; // binary: 0000 1100 (only bits where both a and b are set to 1)

Bitwise OR (|)

The bitwise OR operator sets the result bit to 1 if either of the corresponding input bits is 1. In Java, it is represented as |.

int a = 60; // binary: 0011 1100
int b = 13; // binary: 0000 1101
int result = a | b; // binary: 0011 1101 (set to 1 any bit where either a or b is set to 1)

Bitwise XOR (^)

The bitwise XOR operator sets the result bit to 1 if exactly one of the corresponding input bits is 1. In Java, it is represented as ^.

int a = 60; // binary: 0011 1100
int b = 13; // binary: 0000 1101
int result = a ^ b; // binary: 0011 0001 (set to 1 any bit where either a or b is set, but not both)

Bitwise NOT (~)

The bitwise NOT operator inverts all the bits of a number. In Java, it is represented as ~.

int a = 60; // binary: 0011 1100
int result = ~a; // binary: 1100 0011 (invert all bits)

Bitwise Left Shift (<<)

The bitwise left shift operator shifts the bits of a number to the left by a specified number of positions. In Java, it is represented as <<.

int a = 60; // binary: 0011 1100
int b = 2; // shift by 2 places
int result = a << b; // binary: 0110 0000 (shift bits 2 places to the left)

Bitwise Right Shift (>>)

The bitwise right shift operator shifts the bits of a number to the right by a specified number of positions. In Java, it is represented as >>.

int a = 60; // binary: 0011 1100
int b = 2; // shift by 2 places
int result = a >> b; // binary: 0000 0111 (shift bits 2 places to the right)

Worked Example

In this example, we will demonstrate how to use bitwise operators to implement a simple password verification system.

Password Verification System

public class BitwiseExample {
public static void main(String[] args) {
int password = 123456; // user's password in decimal
int enteredPassword = 120987; // user's entered password in decimal

// convert both password and enteredPassword to binary
String passwordBinary = Integer.toBinaryString(password);
String enteredPasswordBinary = Integer.toBinaryString(enteredPassword);

// perform bitwise XOR on the password and enteredPassword binary representations
String result = passwordBinary ^ enteredPasswordBinary;

// check if the resulting string is equal to the secret key (a pre-defined binary pattern)
String secretKey = "01010101";
boolean validPassword = result.equals(secretKey);

if (validPassword) {
System.out.println("Access granted!");
} else {
System.out.println("Incorrect password! Access denied.");
}
}
}

Common Mistakes

  1. Forgetting to convert binary strings to integers or vice versa when performing arithmetic operations.
  2. Not understanding the difference between bitwise AND (&) and logical AND (&&).
  3. Using bitwise operators on non-integer data types, which will result in a compilation error.
  4. Misusing the bitwise NOT operator (~) to get the absolute value of a number instead of using the unary + operator.
  5. Not accounting for negative numbers when performing bitwise operations, as they have different binary representations than positive numbers.
  6. Failing to handle edge cases, such as zero or all-ones values, when using bitwise operators.
  7. Confusing the left shift (<<) and right rotate (>>) operators, which are not equivalent in Java.
  8. Not checking for arithmetic overflow when performing bitwise operations on large numbers.
  9. Using bitwise operators incorrectly with conditional statements, leading to unexpected results.

Common Mistakes - Subheadings

  1. Incorrect Conversions Between Binary Strings and Integers
  2. Understanding the Differences between Bitwise AND (&) and Logical AND (&&)
  3. Using Bitwise Operators on Non-Integer Data Types
  4. Misusing the Bitwise NOT Operator (~) for Absolute Value Calculation
  5. Handling Negative Numbers in Bitwise Operations
  6. Edge Cases in Bitwise Operations
  7. Confusion between Left Shift (<<) and Right Rotate (>>)
  8. Overflow Errors when Performing Bitwise Operations on Large Numbers
  9. Incorrect Use of Bitwise Operators with Conditional Statements

Practice Questions

  1. Write a Java program that checks if a given number is even or odd using only bitwise operators.
  2. Implement a function that swaps two numbers without using a temporary variable. Use bitwise XOR to achieve this.
  3. Given an array of integers, write a Java method that finds the maximum number with an odd number of set bits (1s) using only bitwise operations.
  4. Write a program that calculates the sum of two numbers without using arithmetic operators (+, -, *, /). Use bitwise operators instead.
  5. Implement a function to count the number of set bits (1s) in an integer using only bitwise operations.
  6. Write a Java program that implements a simple encryption algorithm using bitwise XOR and left shift operations.
  7. Given a binary string, write a Java method to convert it back to its decimal representation using only bitwise operators.
  8. Implement a function to find the first set bit (1) in an integer using only bitwise operators.
  9. Write a program that checks if two integers have any common set bits (1s).
  10. Implement a method that finds the least common multiple of two numbers using only bitwise operations and GCD calculation.
  11. Write a Java program that reverses the order of bits in an integer using only bitwise operators.
  12. Given a binary string, write a Java method to count the number of 0s, 1s, and consecutive runs of 1s (also known as "run-length encoding").

FAQ

Why do we need to use bitwise operators in Java?

Bitwise operators allow developers to perform operations on individual bits of a number rather than the whole value. This can lead to more efficient code, especially when dealing with binary data or memory management tasks. Understanding bitwise operators is essential for mastering low-level programming and solving complex problems efficiently.

What is the difference between bitwise AND (&) and logical AND (&&) in Java?

While both operators compare their operands, bitwise AND compares individual bits, whereas logical AND checks if both operands are true or false as Boolean values.

How can we check if a number is odd using only bitwise operators in Java?

To determine whether a number is odd using bitwise operators, you can perform a bitwise AND operation on the number and 1 (number & 1). If the result is non-zero, the number is odd.

Can we use bitwise operators with floating-point numbers in Java?

No, bitwise operators are only applicable to integers. When you perform bitwise operations on floating-point numbers, Java will automatically convert them to integers, which may lead to unexpected results due to the loss of precision.

What is the difference between left shift (<<) and right rotate (>>) in Java?

Left shift (<<) shifts bits to the left by a specified number of positions, while filling empty spaces with zeros. Right rotate (>>) shifts bits to the right by a specified number of positions, but fills empty spaces with the sign bit for negative numbers or zeros for positive numbers.

How can we implement a simple encryption algorithm using bitwise operators in Java?

To create a simple encryption algorithm using bitwise operators, you can use XOR (^) to perform the encryption and decryption operations. For example:

public class SimpleEncryption {
private static final int KEY = 0b10101010; // pre-defined key

public static void main(String[] args) {
int message = 42; // plaintext message in decimal
int encryptedMessage = encrypt(message);
int decryptedMessage = decrypt(encryptedMessage);

System.out.println("Plaintext: " + message);
System.out.println("Encrypted: " + encryptedMessage);
System.out.println("Decrypted: " + decryptedMessage);
}

public static int encrypt(int message) {
return message ^ KEY; // XOR the key and the message to encrypt it
}

public static int decrypt(int encryptedMessage) {
return encryptedMessage ^ KEY; // XOR the key and the encrypted message again to decrypt it
}
}
List of Java Bitwise Operators | Java | XQA Learn