Summarise With AI
ChatGPT
Perplexity
Claude
Gemini
Grok
ChatGPT
Perplexity
Claude
Gemini
Grok
Back

Understand How the Bitwise Operator in Java Works

22 Nov 2025
5 min read

What this blog covers (and why you’ll care)

  • How each bitwise operator actually behaves at the binary level (with visuals you’ll never forget).
  • Real Java examples for AND, OR, XOR, NOT, Left Shift, Right Shift & Unsigned Right Shift.
  • Truth tables + binary representations that decode exactly how operators transform your numbers.
  • Where bitwise operators are used in the real world, encryption, graphics, flags, masks, networking & performance hacks.
  • Difference between bitwise operators vs logical operators, and why confusing them breaks your code.
  • Practical code demos: counting set bits, checking power of two, swapping bits, understanding 2’s complement & more.

If you have ever wondered, “How does Java actually see my numbers?”, this is the blog that finally answers it.

Introduction

Most Java developers rely heavily on arithmetic and logical operators, but only a few truly explore the hidden power buried one layer deeper: bitwise operations.

If you have ever wondered how encryption works, why graphics render fast, or how systems manage memory efficiently, the answer lies in the bitwise operator in Java. They’re the invisible gears of performance-critical software.

In this blog, you will learn how the bitwise operator in Java worksfrom AND, OR, XOR to shifting, masking, and solving real-world bit manipulation problems, all explained simply.

“If you can control the bits, you can control everything.”

What are Bitwise Operators?

Bitwise operators in Java let you work directly with the individual bits that make up a number. Since computers store everything as 1s and 0s, these operators give you precise control over that binary data, allowing you to flip bits, compare them, or shift them in any direction.

They play a major role in areas where performance and memory efficiency matter the most: operating systems, networking, embedded systems, encryption, servers, and even database engines. Whenever you need low-level control or want your code to run as fast and efficiently as possible, bitwise operators become essential.

Why are Bitwise Operators Used in Java?

The bitwise operator in Java is frequently used when working with data at a low level and in detail. It allows you to work with individual bits of a number, which is very helpful for things like memory conservation, performance optimization, and direct hardware interaction.

What is the purpose of the bitwise operators in Java, then? Speed is a major factor. It may be quicker to shift or AND bits than to conduct standard arithmetic or logical operations. Bitwise operators give you an efficient approach to handle information in real-time or when working with large amounts of data. Additionally, they are effective for situations when memory consumption is essential. You can store more data in less space by utilizing bits rather than full numbers.

How Do They Work?

In Java, each number is stored as a series of bits (0s and 1s). This Java bitwise operators tutorial, which is the subject of this, enables you to perform the operations directly on these bits. For instance, the AND operator (&) is used to compare each of the bits in two numbers and give back 1 only if both are 1. The OR (|) operator returns a 1 if one of the bits is 1. Shifting acts as a mode of operation where the bits are moved left or right, equivalent to multiplying or dividing the number by powers of two.

In short, bitwise operator in Java allow you to manipulate the low-level nature of the data, which helps you improve the speed, efficiency, and flexibility of your code.

Types of Bitwise Operator in Java

Let's learn about the different types of bitwise operators in Java, explore how they work, and look at some examples.

1. Bitwise AND (&) Operator

The bitwise AND operator in Java compares the corresponding bits of two integers for each of them and generates a 1 only if both bits are 1. Please note that if either or both bits are 0, the result will be 0.

Let's take:

  • 12 in binary → 1100
  • 5 in binary → 0101

Now, line them up and apply AND:

   1100   (12)
& 0101   (5)
--------
   0100   (result)

What does 0100 mean?

That’s 4 in decimal.

So, 12 & 5 = 4

Easy Way to Remember:

  • Bitwise AND only gives 1 when both bits are 1.
  • That’s why 12 & 5 becomes 4

Example:

public class BitwiseANDExample {
    public static void main(String[] args) {
        int a = 12; // 1100 in binary
        int b = 5;  // 0101 in binary
        int result = a & b; // Perform AND operation

        System.out.println("a & b = " + result); // Output the result
    }
}

Output

a & b = 4

Explanation

  • 12 in binary is 1100
  • 5 in binary is 0101
  • When you perform a bitwise AND, only the bits that are 1 in both numbers remain 1. So, 1100 & 0101 result in 0100, which is 4 in decimal.

2. Bitwise OR (|) Operator

When the bitwise OR operator is used to compare two numbers, the outcome is 1 if at least one of the associated bits is 1. The outcome is 0 if both bits are 0.

Bitwise OR (|) operation using:

a = 12  → Binary: 1100  

b = 5   → Binary: 0101

Now apply the bitwise OR:

 1100   (12 in binary)  
|0101   (5 in binary)  
--------
  1101   (Result is 13 in decimal)

Bit-by-bit comparison:

1 | 0 = 1
1 | 1 = 1
0 | 0 = 0
0 | 1 = 1

So, the binary result is 1101, which equals 13 in decimal.

Therefore, 12 | 5 = 13.

Example

public class BitwiseORExample {
    public static void main(String[] args) {
        int a = 12; // 1100 in binary
        int b = 5;  // 0101 in binary
        int result = a | b; // Perform OR operation

        System.out.println("a | b = " + result); // Output the result
    }
}

Output

a | b = 13

Explanation

  • 12 in binary is 1100
  • 5 in binary is 0101
  • When you perform a bitwise OR, the result is 1 if at least one of the bits is 1. So, 1100 | 0101 results in 1101, which is 13 in decimal.

3. Bitwise XOR (^) Operator

When two integers' corresponding bits are compared using the bitwise Java XOR operator (exclusive OR), if the bits differ, the result is 1. The outcome is 0 if the bits are identical.

Let’s take 

  • a = 12 → Binary: 1100
  • b = 5 → Binary: 0101

Now let’s apply the bitwise XOR ( ^ ) operator:

 1100   (12 in binary)
^0101   (5 in binary)
--------
 1001   (Result in binary = 9 in decimal)

Final result:

12 ^ 5 = 9

Explanation:

1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1

Only the bits that are different become 1, and others become 0.

Example:

public class BitwiseXORExample {
    public static void main(String[] args) {
        int a = 12; // 1100 in binary
        int b = 5;  // 0101 in binary
        int result = a ^ b; // Perform XOR operation

        System.out.println("a ^ b = " + result); // Output the result
    }
}

Output

a ^ b = 9

00001100  →  this is 12 in binary

  1. Apply bitwise NOT (~): flip all bits

11110011

  1. Now, 11110011 is a negative number in Java (since the first bit is 1).
    To find out which negative number it is, do the two's complement:

a. Invert the bits again:

00001100

b. Add 1:

00001100 + 1 = 00001101 → 13

So, 11110011 is -13 in decimal.

  1. Final result:

~12 = -13

Example

Explanation

  • 12 in binary is 1100
  • 5 in binary is 0101
  • If the bits are different, the XOR operation yields 1. Therefore, 1100 ^ 0101 yields 1001, or 9 in decimal.

4. Bitwise NOT (~) Operator

Every bit in the operand is inverted by the bitwise NOT operator. To put it simply, it converts all 1s to 0s and all 0s to 1. Another name for this is the bitwise complement.

Let's take a = 12 and apply the bitwise NOT (~) operator step by step.

  1. Write 12 in 8-bit binary:
00001100  →  this is 12 in binary
  1. Apply bitwise NOT (~): flip all bits
11110011
  1. Now, 11110011 is a negative number in Java (since the first bit is 1).

To find out which negative number it is, do the two's complement:

a. Invert the bits again:

00001100

b. Add 1:

00001100 + 1 = 0000110113

So, 11110011 is -13 in decimal.

  1. Final result:
~12 = -13

Example

public class BitwiseNOTExample {
    public static void main(String[] args) {
        int a = 12; // 1100 in binary
        int result = ~a; // Perform NOT operation
        System.out.println("~a = " + result); // Output the result
    }
}

Output

~a = -13

Explanation:

  • 12 in binary is 1100
  • Java utilizes two's complement to express negative numbers; therefore, even if the NOT operation flips all the bits, turning 1100 into 0011, the decimal output is -13.

5. Left Shift (<<) Operator

The left shift operator shifts an integer's bits left by a certain number of places. Each shift to the left by one position is the same as multiplying the number by 2. This is how the left-shift operator operates to fill the rightmost bits with zeros.

Here's the simple calculation for left shifting a = 5 by 1 position:

Given:

a = 5

Binary of 5 = 0000 0101

Left Shift Operation:

a << 1 means shift all bits to the left by 1 position:

0000 0101 << 1 = 0000 1010

Result:

0000 1010 = 10 (in decimal)

So,

5 << 1 = 10

Explanation: 

Each left shift multiplies the number by 2.

So, 5 << 1 = 5 * 2 = 10, and that’s exactly what we got.

Example

public class LeftShiftExample {
    public static void main(String[] args) {
        int a = 5; // 0101 in binary
        int result = a << 2; // Shift left by 2 positions

        System.out.println("a << 2 = " + result); // Output the result
    }
}

Output

a << 2 = 20

Explanation

  • 5 in binary is 0101
  • If you move two places to the left, you get 10100, which is 20 in decimal.

6. Right Shift (>>) Operator

The right shift operator shifts the bits of a number to the right by a number of positions that is specified. Each shift to the right by one position is equivalent to dividing by 2. The leftmost bits (the sign bit) are filled with the original sign bit for signed numbers.

Let’s break it down simply using a = 20 and the right shift operator >>.

Binary of 20 = 0001 0100

Operation: a >> 1

  • This shifts all bits one place to the right
  • The leftmost bit (sign bit) is filled with 0 (since 20 is positive)
  • The rightmost bit is dropped
Before shift: 0001 0100  (20)
After shift:  0000 1010  (10)

So,

int a = 20;
int result = a >> 1// result = 10

Explanation:

Each right shift divides the number by 2.

  • 20 >> 1 = 10
  • 20 >> 2 = 5
  • 20 >> 3 = 2 (integer division)

That’s how right shift works, simple and efficient.

Example

public class RightShiftExample {
    public static void main(String[] args) {
        int a = 20; // 10100 in binary
        int result = a >> 2; // Shift right by 2 positions

        System.out.println("a >> 2 = " + result); // Output the result
    }
}

Output

a >> 2 = 5

Explanation

  • You start with a = 20, which is 10100 in binary.
  • The code shifts the bits of a 2 places to the right (a >> 2).
  • Shifting 2 places to the right is like dividing 20 by 4 (because each right shift divides by 2).
  • So, 20 / 4 = 5.

The program will print 5, as the right shift operation divides the number by 4.

7. Unsigned Right Shift (>>>) Operator

Regardless of sign, the unsigned right shift operator shifts the bits to the right and adds zeros to the leftmost bits. This method can be used when unsigned data types are in use.

Let’s break it down simply using a = -20 and the unsigned right shift operator (>>>) in Java.

Value:

int a = -20;
int result = a >>> 2;
System.out.println(result);

Explanation:

  1. Binary of -20 (32-bit representation using two’s complement):
-20 = 11111111 11111111 11111111 11101100
  1. Unsigned Right Shift by 2 (>>> 2)
  • Shifts all bits 2 positions to the right
  • Fills leftmost bits with 0s, not the sign bit
  • So we get:
00111111 11111111 11111111 11111011
  1. Result in Decimal:
= 1073741819

Example

public class UnsignedRightShiftExample {
    public static void main(String[] args) {
        int a = -20; // 11111111111111111111111111101100 in binary (two's complement)
        int result = a >>> 2; // Unsigned right shift by 2 positions

        System.out.println("a >>> 2 = " + result); // Output the result
    }
}

Explanation:

  • -20 in two's complement is 11111111111111111111111111101100
  • After shifting two positions to the right, the leftmost bits are filled with 0s, and the result is a large positive number (1073741815).

Output

a >>> 2 = 1073741815

Quick Recap

Bitwise Operators in Java
Operator Symbol What It Does Simple Meaning Example Result
Bitwise AND & Compares each bit and returns 1 only if both bits are 1 “Both must be true” 12 & 5 = 4
Bitwise OR | Returns to 1 if at least one of the bits is 1 “Either is enough” 12 | 5 = 13
Bitwise XOR ^ Returns 1 when bits are different “True if different” 12 ^ 5 = 9
Bitwise NOT ~ Flips every bit (0→1, 1→0) “Invert everything” ~12 = -13
Left Shift << Shifts bits left, filling right with 0 Multiply by 2ⁿ 5 << 1 = 10
Right Shift (Signed) >> Shifts bits right, preserving sign Divide by 2ⁿ 20 >> 1 = 10
Unsigned Right Shift >>> Shifts bits right, filling left with 0 Always a positive shift -20 >>> 2 = 1073741815

Truth Tables and Binary Representation

Bitwise operations are best understood by visualizing how they work at the binary level. Truth tables and binary representations help clarify exactly how each bitwise operator affects the bits of its operands. This section covers how to represent numbers in binary, how the core bitwise operators work bit by bit, and how truth tables can be used as a reference for their behavior.

Binary Representation of Integers

In Java, integers are stored as sequences of bits (0s and 1s). For example:

  • 5 in binary: 0101
  • 12 in binary: 1100
  • 29 in binary: 11101

When you apply bitwise operations, you are manipulating these binary digits directly.

Truth Tables for Bitwise Operators

Below is the simplest truth table showing how AND (&), OR (|), and XOR (^) behave for every combination of two bits:

Bitwise Operations Truth Table
a b a & b a | b a ^ b
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Meaning

  • AND (&) → 1 only if both bits are 1
  • OR (|) → 1 if any bit is 1
  • XOR (^) → 1 if the bits are different

NOT (~) Operator

Unary operator → flips each bit

  • 0 → 1
  • 1 → 0

Visualizing Bitwise Operations with Binary Output

Let’s see how these operators work with actual numbers:

Example: Bitwise AND

a = 12 → 1100

b = 5  → 0101

12 & 5:
1100
0101
----
01004

Example: Bitwise OR

12 | 5:
1100
0101
----
110113

Example: Bitwise XOR

12 ^ 5:
1100
0101
----
10019

Example: Bitwise NOT

a = 5 → 0000 0101 (8 bits)

~a:
1111 1010 → -6 (two's complement)

Why Use Truth Tables and Binary Output?

  • Clarity: Truth tables provide a quick reference for how each operator works at the bit level.
  • Debugging: Printing numbers in binary (using Integer.toBinaryString(num)) helps visualize and debug bitwise logic.
  • Learning: These representations make it easier to reason about and predict the results of bitwise operations.

Use Cases and Applications of Bitwise Operators in Java

Bitwise operators are used extensively in programming and applications, particularly where hardware interface, memory, or execution efficiency are crucial. They are not only an academic subject. Here are a few instances of the most typical and valuable applications for bitwise operators:

1. Setting, Clearing, and Toggling Bits (Flags and Permissions)

You can effectively bundle all of your boolean flags into a single integer value by using bitwise operators for flag management. This is helpful when storing features, toggles, hardware register settings, and permissions.

  • Set a bit:
number = number | (1 << n); // Sets the nth bit to 1
  • Clear a bit:
number = number & ~(1 << n); // Clears the nth bit (sets to 0)
  • Toggle a bit:
number = number ^ (1 << n); // Flips the nth bit

Example:
Managing user permissions (read, write, execute) using bits in a single integer.

2. Bit Masking

Bit masking is used to obtain, set, or clear a value of individual bits. Bit masking is ubiquitous in protocols, graphics, and embedded systems.

  • Extract lower 4 bits:
int lowerNibble = number & 0x0F;
  • Check if a specific flag is set:
boolean isSet = (number & (1 << n)) != 0;

3. Efficient Arithmetic Operations

Bit shifts are a fast way to multiply or divide integers by powers of two.

  • Multiply by 2:
result = number << 1;
  • Divide by 8:
result = number >> 3;

In terms of speed, this will typically be more efficient than using multiplication or division, and it could even be more effective than other translation techniques, especially in code that is performance-critical.

4. Compact Storage

 Bitwise operators allow for packing multiple booleans, or small integers, into a single variable from a memory perspective. This is beneficial in embedded systems and applications that must comply with strict memory limitations.  

Example: Store up to 32 boolean flags in single variable, using an integer data type.

5. Cryptography and Encryption

Bitwise XOR (^) and other bitwise operations form the basis of many encryption algorithms and hash algorithms. Bitwise manipulation is synonymous with the obfuscation of the assembly of information on a binary basis.

6. Compression and Data Encoding

Bitwise operations are used to compress data, encode information efficiently, and implement custom binary protocols. They enable you to neatly pack data by manipulating individual bits.

7. Error Detection and Correction

Checksums, parity computations, and error correction codes (such as Hamming codes) use bitwise operations to identify and fix problems during transmission or storage. 

8. Network Programming

Subnet masks, protocol flags, and IP addresses may all be changed using bitwise operators. For instance, bit masking and shifting are required when dividing an IP address into its network and host components. 

9. Hardware and Embedded Systems

Setting, clearing, or toggling bits in particular hardware register bits is sometimes required when working directly with hardware. Bitwise operators provide the incredibly precise control needed for device driver development or low-level programming.

Summary

Bitwise operators are essential tools for:

  • Managing flags and permissions
  • Packing data efficiently
  • Performing fast arithmetic
  • Implementing cryptographic and compression algorithms
  • Working with hardware, protocols, and error detection

When you understand the role of bitwise operators, you can write more efficient, powerful, and scalable Java programs, especially those that require systems programming, networking, and runtime efficiency.

Difference Between Bitwise Operator in Java vs. Logical Operators in Java

Here’s a comparison between Bitwise Operators and Logical Operators in Java:

Bitwise Operators vs Logical Operators
Aspect Bitwise Operators Logical Operators
Operation Level Works at the bit level of integer values (like int, long, byte). Works on boolean expressions (true/false values).
Common Operators & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift) && (AND),
Use Case Used for manipulating individual bits in binary numbers, such as setting flags or performing bit manipulation tasks. Used for combining or negating boolean conditions, often in control flow and decision-making.
Data Types Works with int, long, byte, and short types. Works with boolean values (true/false).
Result Produces a result based on binary operations, usually an integer value. Returns a boolean value (true or false).
Evaluation Operates on each bit of the operand individually. Operates on the entire boolean expression.
Performance Faster for tasks that need direct bit manipulation (e.g., encryption). More suitable for logical conditions in programs.
Example a & b, a | b, a ^ b, a << 1 a && b, a

Example:

Bitwise Operator:

int a = 5;  // 0101 in binary  
int b = 3;  // 0011 in binary  
System.out.println(a & b);  // Output: 1 (0001 in binary)

Logical Operator:

boolean a = true;  
boolean b = false;  
System.out.println(a && b);  // Output: false

Advantages of Bitwise Operators in Java

Advantages of Bitwise Operators in Java

Bitwise operators in Java offer several advantages, especially when working with low-level programming, performance-critical code, or system-level applications. Here are the key advantages of using bitwise operators in Java:

  1. Faster Execution

Bitwise operators work on binary data, so they will execute faster than other types of operations. They provide a real benefit in performance-critical scenarios like games and encryption.

  1. Saves Memory

Bitwise operations will also benefit memory usage, since they allow you to operate on smaller pieces of data, such as modifying a single bit of data, instead of larger variables.

  1. Precise Control Over Data

Using bitwise operators provides direct control over each individual bit of the data you are working with. This could be useful when you need to set, clear, or query whether an individual bit is on or off, such as flagging on or off, or masking with bits.

  1. Efficient for Low-Level Tasks

Bitwise operators are essential in low-level programming, like interacting with hardware or creating custom protocols, where performance and precision matter most.

  1. Quicker Arithmetic

For certain operations, like multiplying or dividing by powers of two, bitwise shifts can do the job much faster than regular multiplication or division.

Disadvantages of Bitwise Operators in Java

Below are several of the major disadvantages of bitwise operations in Java:

  1. Hard to Understand

Bitwise operations can be confusing for beginners, which is even more true if you're not comfortable with binary numbers and low-level programming.

  1. Difficult to Debug

Since bitwise operations often involve complex expressions with binary data, they can be harder to debug, making it challenging to track down issues.

  1. Not Always Needed

Bitwise operations are unnecessary in many cases and can unduly complicate basic software when used in minor applications.

  1. Can Be Error-Prone

Bitwise operations are prone to mistakes since it is simple to use the incorrect mask or shift bits the incorrect amount of times, which can result in complexity or unexpected consequences.

  1. Less Readable Code

Code using bitwise operators can be more challenging to read and understand, especially for others who are unfamiliar with this kind of operation.

Common Bit Manipulation Problems

Bit manipulation is a powerful set of techniques that uses low-level binary operations to solve problems more efficiently. These tricks often yield faster, more memory-efficient solutions than relying purely on arithmetic or loops. 

Why it matters

  • Bitwise operations (AND &, OR |, XOR ^, NOT ~, shifts <</>>) act directly on the binary representation of numbers and are often implemented in a single CPU cycle.
  • These techniques aid in tasks such as counting the number of flags set, subsetting and modifying a data structure, optimizing loops, or using other algorithmic tricks during coding interviews.
  • When it comes to competitive programming and system design, simply knowing how to use bit masks, shifts, and toggles puts you at a much more advantageous position.

Key Terms & Techniques

  • Hamming weight: The number of set bits (1s) in the number is known as the Hamming weight.
  • Bit masking is the process of setting or unsetting bits in a number using a mask, such as 1 << n.
  • Bit shifting: The right shift >> divides (floor) by powers of two, whereas the left shift << multiplies by powers of two.
  • Bitwise AND, OR, and XOR are helpful for merging sets, toggling bits, and verifying flags.
  • Clear the nth bit: e.g., x & ~(1 << n) clears bit n
  • Compact storage: Storing multiple boolean flags in a single integer via bits
  • Power of two: Numbers which have exactly one set bit (e.g., 2, 4, 8…)
  • Swap odd and even bits, Swap two bits: Specific bit-manipulation operations useful in puzzles & optimization

Typical Problems to Practice

Here are a few standard problems where bit manipulations shine:

Common Bit Manipulation Problems
Problem Description What to Use
Check if a number is a power of two Determine if n is exactly one bit set (n & (n - 1)) == 0 && n > 0
Count set bits (Hamming weight) Given an integer, count how many 1s in its binary form while(n) { n &= (n - 1); count++; }
Bitwise masking Set/clear/toggle specific bits in an integer Use `&`, `|`, `^` with bit masks
Swap odd and even bits Given a number, swap its even-positioned bits with odd-positioned bits Use masks & shifts
Left/right shifts for multiply/divide by 2ⁿ Multiply/divide by powers of two without arithmetic Use << or >>
Bitwise and on flags/compact storage Store multiple true/false flags in one integer Use different bit positions for each flag
Count the different bits between two numbers How many bit positions differ between a and b Use xor = a ^ b; then count set bits in xor

Approach & Tip Sheet

  • Visualize the bits: Always think in binary when solving these.
  • Ask: “Which bit(s) does this operation affect?”
  • Use masks: 1 << n gives you a mask with only the nth bit set.
  • Use the n & (n - 1) trick to clear the lowest set bit.
  • Be careful with signed vs unsigned shifts; know your language specifics.
  • Test edge cases: all bits zero, all bits one, maximum/minimum integers.
  • Efficiency: bit operations are O(1); that means good performance for large input sizes.

Remember: By mastering these tricks and typical problems, you’re not just solving puzzles, you’re building low-level intuition that can make your code faster, leaner, and more elegant. Use these techniques in your next algorithm challenge or system-design interview and watch the difference.

Practical Examples and Code Demonstrations on Bitwise Operator in Java

It makes understanding bitwise operators much easier when you get to see them in action. To that end, this section provides practical examples from Java code, so you can better understand each major bitwise operator with its outputs and explanations. In addition to seeing this code example, the demonstrations will help solidify your understanding of how each operator manipulates binary data and how it returns to decimal.

1. Count Set Bits (Hamming Weight)

Problem

Write a program to count the number of 1s in the binary form of a number.

Code

public class HammingWeight {
public static void main(String[] args) {
int num = 29; // 11101
int count = 0;
while (num != 0) {
num &= (num - 1); // clear the lowest set bit
count++;
}
System.out.println("Set Bits = " + count);
}
}

Explanation

This code counts how many 1s are present in the binary form of a number (called the Hamming Weight). The number 29 is 11101 in binary, which has four 1s. Instead of checking every bit, the code uses a smart trick: num &= (num - 1) removes the lowest set bit in each loop. Each time a 1-bit is removed, the counter increases. This continues until all 1s are gone and num becomes 0. Since 29 has four 1s, the loop runs four times, and the program prints “Set Bits = 4”.

Output

Set Bits = 4

2. Check if a Number Is a Power of Two

Problem

Determine if a number is a power of two using bit operations.

Code

public class PowerOfTwoCheck {
    public static void main(String[] args) {
        int n = 32;

        // Check if n is a power of two
        boolean isPower = (n & (n - 1)) == 0 && n > 0;

        System.out.println(isPower);
    }
}

Explanation

This code checks whether a number is a power of two using a classic bitwise trick. A number like 1, 2, 4, 8, 16, 32… has only one set bit in its binary form. The expression (n & (n - 1)) removes the lowest set bit. For powers of two, this results in 0, because there’s only one 1-bit to remove. The code also checks that n > 0 because negative numbers and zero cannot be powers of two. For n = 32, which is 100000 in binary, the condition becomes true, so the program prints true.

Output

true

3. Swap Odd and Even Bits

Problem

Swap every odd-positioned bit with its neighbouring even bit.

Code

public class SwapOddEvenBits {
    public static void main(String[] args) {
        int n = 23; // binary: 10111

        int evenMask = 0xAAAAAAAA; // mask even bits
        int oddMask = 0x55555555;  // mask odd bits

        int evenBits = (n & evenMask) >>> 1;
        int oddBits = (n & oddMask) << 1;

        int result = evenBits | oddBits;

        System.out.println(result);
    }
}

Explanation

This program swaps the odd and even bits of number 23. In binary, 23 is 10111. The program uses a couple of masks (evenMask denotes 0xAAAAAAAA) to "isolate" the even-position bits, and oddMask (0x55555555) to isolate the odd-position bits. Then, the program shifts the even bits right and the odd bits left to swap their positions. Finally, it combines them together using OR (|). After swapping the bits of the number 23, the value of the resulting integer after the swap will be printed.

Output

43

4. Demonstrate 2’s Complement Using Bitwise Complement (~)

Problem

Show how Java converts a bitwise NOT result into a negative number using 2’s complement.

Code

public class TwosComplementDemo {
    public static void main(String[] args) {
        int num = 10;          // 00001010
        int result = ~num;     // flips bits

        System.out.println(result);
    }
}

Explanation 

The program shows how the bitwise NOT operator (~) works, specifically with two's complement. The number 10 is written in binary as 00001010. When using ~num, all of the bits are flipped from binary zero to binary one, resulting in 11110101. In Java, and other programming languages, numbers use two's complement for storage, and thus, a binary number with a starting one has a negative decimal representation. So, 11110101 = -11 in decimal form. This is why the program prints -11, as it is simply the negative representation of the two's complement of the bits.

Output

-11 

Note: 

These examples go beyond theory and show how bitwise operators actually solve real interview-ready problems. They educate Java developers patterns that are common for both coding rounds and viva examinations, such as how to clear bits, recognize powers of two, comprehend 2's complement, and perform efficient operations. These are the most useful examples that will help you build a strong bit-manipulation intuition.

Conclusion

Bitwise operators in Java may not be used daily, but they’re essential whenever speed, memory efficiency, and low-level control matter. Knowing how to work at the bit level makes you a stronger Java developer, especially in optimization-heavy areas like competitive programming, game development, security, and embedded systems.

Points to Remember

  • Bitwise operations work directly on binary data, fast and efficient.
  • Ideal for hardware interaction, optimization, and cryptographic logic.
  • XOR tricks (swap, odd occurrence) are common interview favorites.
  • Shifts (<<, >>, >>>) act like quick multiply/divide by powers of two.
  • Understanding binary and two’s complement is key to avoiding errors.

Frequently Asked Questions

1. What is a bitwise operator with an example?

Bitwise operators are the ones that perform operations with the individual bits of binary numbers.

Example: 6 & 3 (Binary: 0110 & 0011 = 0010 → Output: 2).

2. When to use bitwise operators?

Utilize bitwise operators in hardware-level programming, cryptography, graphics processing, low-level programming, and optimization.

3. Why are bitwise operators faster?

The hardware does not make any other calculations; it processes the binary data directly, which is why faster results are guaranteed.

4. What is the XOR condition?

XOR (^) returns 1 if two bits are different and 0 if they are the same.

Example: 6 ^ 3 (Binary: 0110 ^ 0011 = 0101 → Output: 5).

5. How does bitwise NOT work?

The bitwise NOT (~) inverts each bit of a number, turning 0s into 1s and vice versa.

Example: ~6 (Binary: 0110 → 1001, which is -7 in two’s complement).

6. What is a Boolean operator?

Bitwise operators operate at the binary level, whereas boolean operators (&&, ||,!) operate on true/false values.

Read More Articles

Chat with us
Chat with us
Talk to career expert