Bitwise Operators in Java

Learn Java bitwise operators: AND, OR, XOR, NOT, and shifts, with fixed-width masks, flag examples, right-shift behavior, and safe cryptography guidance.

published: reading time: 13 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn Java bitwise operators: AND, OR, XOR, NOT, and shifts, with fixed-width masks, flag examples, right-shift behavior, and safe cryptography guidance.

Bitwise Operators in Java

Bitwise operators manipulate individual bits in Java’s fixed-width integer types. They are useful for flags, masks, and data formats with a defined bit layout.

Introduction

Java provides & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (signed right shift), and >>> (unsigned right shift). These operators are handy when a value has a documented bit layout, such as a set of flags or a binary field. Prefer ordinary arithmetic when it communicates the intent more clearly. If a bitwise expression is meant to improve performance, measure the relevant code before keeping the less familiar form.

Right shifts differ in how they fill the high bits. -4 >> 1 is -2 because >> copies the sign bit. -4 >>> 1 is 2147483646 because >>> fills from the left with zeroes. Also, ^ means XOR, not exponentiation: 2 ^ 3 evaluates to 1. Use Math.pow(2, 3) when you need exponentiation.

Bit flags are a common application. Give each flag a distinct power-of-two value, combine flags with OR, and test a flag with AND. For example, permissions & FLAG_READ is nonzero when the read flag is set. The hexadecimal masks below make each selected bit visible. For cryptographic algorithms, use vetted Java cryptography APIs and providers.

When to Use / Not to Use

Use bitwise operators when:

  • Working with flags and bit masks (e.g., file permissions, configuration)
  • Representing compact sets of flags when the bit layout is documented
  • Encoding/decoding data at the bit level

Do not use bitwise operators when:

  • Working with non-integer types without explicit conversion
  • A normal arithmetic or boolean expression makes the intent clearer
  • A performance claim has not been measured in the relevant workload
  • A signed value’s behavior is unclear; document whether the bits or numeric value matter

Diagram: Bitwise Operations at the Bit Level

graph LR
    A["1010"] --> B["& AND"]
    C["1100"] --> B
    B --> D["1000"]

    E["1010"] --> F["| OR"]
    C --> F
    F --> G["1110"]

    H["1010"] --> I["^ XOR"]
    C --> I
    I --> J["0110"]

    K["1010"] --> L["~ NOT"]
    L --> M["0101"]

    N["0101 << 1"] --> O["1010"]
    P["1010 >> 1"] --> Q["0101"]

Code Snippet: Flags and Masks Pattern

public class BitwiseDemo {
    // int is 32 bits; long is 64 bits in Java.
    public static final int FLAG_READ = 0x0000_0001;
    public static final int FLAG_WRITE = 0x0000_0002;
    public static final int FLAG_EXECUTE = 0x0000_0004;
    public static final int FLAG_ADMIN = 0x0000_0008;
    private static final int MASK_LOW_BYTE = 0x0000_00FF;
    private static final long MASK_LOW_32_BITS = 0x0000_0000_FFFF_FFFFL;

    public static void main(String[] args) {
        int permissions = FLAG_READ | FLAG_WRITE;

        // Check if a flag is set
        boolean canRead = (permissions & FLAG_READ) != 0;
        boolean canExecute = (permissions & FLAG_EXECUTE) != 0;

        // Add a flag
        permissions |= FLAG_EXECUTE;

        // Remove a flag
        permissions &= ~FLAG_EXECUTE;

        // Toggle a flag
        permissions ^= FLAG_EXECUTE;

        // Signed right shift vs unsigned
        int negative = -4;
        System.out.println(">> 2: " + (negative >> 2)); // -1 (sign-extended)
        System.out.println(">>> 2: " + (negative >>> 2)); // 1073741823 (zero-filled)

        // Use whichever expression makes parity clearest in context.
        int number = 42;
        boolean evenWithRemainder = number % 2 == 0;
        boolean evenWithMask = (number & 0x0000_0001) == 0;

        // Masks extract selected fields from fixed-width values.
        int lowByte = permissions & MASK_LOW_BYTE;
        long packed = 0x1234_5678_9ABC_DEF0L;
        long low32Bits = packed & MASK_LOW_32_BITS;
    }
}

Save this as BitwiseDemo.java, then run javac BitwiseDemo.java && java BitwiseDemo. Its two printed lines are:

>> 2: -1
>>> 2: 1073741823

Failure Scenarios

Scenario Problem Solution
Using >> on negative numbers The sign bit is copied into the high-order bits Use >>> when zero-fill is intended
Confusing ^ with exponentiation ^ is XOR, not a power operator Use Math.pow() for exponentiation
Reusing a flag bit Two flags then represent the same state Assign each flag a distinct bit
Shift distance is outside width Java masks the distance; int uses its low 5 bits and long its low 6 bits Validate or normalize the distance explicitly

Trade-off Table

Operator Description Use Case
& Bitwise AND Test or extract selected bits
| Bitwise OR Set selected flag bits
^ Bitwise XOR Toggle selected bits
~ Bitwise NOT Invert all bits in an int or long
<< Left shift Move bits toward higher positions
>> Signed right shift Shift right while copying the sign bit
>>> Unsigned right shift Shift right while filling with zero bits

Observability Checklist

  • Log flag state changes for permission-related operations
  • Add assertions when checking flag combinations
  • Avoid logging secrets or raw sensitive bit fields
  • Monitor for unexpected signed shift behavior in negative number paths
  • Add unit tests for bitmask operations covering edge cases

Security Notes

  • Bit-level permission checks: A bitmask check does not make a check-then-act sequence atomic. Protect the whole operation when concurrent changes are possible.
  • Flag manipulation in access control: Keep flag values distinct and document their meaning.

Cryptography

Bitwise operators are appropriate for parsing a documented binary format. Implementing encryption, signatures, hashes, or message authentication by hand is a different task and can introduce security flaws. Use vetted Java Cryptography Architecture (JCA) APIs through providers, following the Java SE 27 JCA guide instead.

Pitfalls

  1. Sign extension with >>: -4 >> 1 returns -2, not 2. Use >>> for logical shift.
  2. ^ is XOR, not exponentiation: 2 ^ 3 returns 1, not 8. Use Math.pow().
  3. Shift distance: A negative or oversized distance is masked by Java. For int, only the low 5 bits are used; for long, the low 6 bits are used. The sign of the value being shifted is a separate concern.
  4. Bitwise ops on negative numbers: Results can be counterintuitive. Document assumptions.
  5. Operand types: Integer bitwise and shift operations use int or long operands; byte, short, and char values are promoted to int. Boolean &, |, and ^ are also supported.

Quick Recap Checklist

  • Assign each flag a distinct bit and use a typed mask for it.
  • Choose >> or >>> based on whether sign extension or zero-fill is required.
  • Remember that Java masks shift distances to the width of int or long.
  • Prefer clear arithmetic for ordinary numeric operations; benchmark before claiming a bitwise form is faster.
  • Use JCA APIs and providers for cryptographic operations.

Interview Questions

1. What is the difference between `>>` and `>>>` in Java?
`>>` is signed right shift and copies the sign bit. `-4 >> 1` is `-2`. `>>>` fills from the left with zeroes, so `-4 >>> 1` is `2147483646`. Use it when zero-fill is part of the bit-level operation; use `Integer.toUnsignedLong` when you need an unsigned numeric interpretation of an `int`.
2. How do you check if a specific bit is set in a number?
Use AND with a mask that has the target bit set. For bit 3, define `private static final int BIT_3 = 0x0000_0008;` and check `(value & BIT_3) != 0`. The explicit hexadecimal value makes the mask's bit position easy to see.
3. What is the XOR swap algorithm and why doesn't it always work?
XOR swap uses `a ^= b; b ^= a; a ^= b;` to exchange two values without a temporary. If both operands refer to the same storage, such as the same array element, the first operation clears that value. A temporary variable is usually easier to read, and there is no general reason to expect XOR swap to be faster.
4. What is a bitmask and when would you use one?
A bitmask is a number with specific bits set used to extract, set, or toggle bits in another number. Common uses include storing independent flags in an integer or checking several states represented by a documented bit layout.
5. What does `~5` evaluate to in Java?
`~5` evaluates to `-6` as an `int`. The complement flips all 32 bits: `00000000000000000000000000000101` becomes `11111111111111111111111111111010`, which represents `-6` in two's complement.
6. What is the result of `1 << 3`?
`1 << 3` is `8` for an `int`: it moves the set bit three positions to the left. In Java source, `^` means XOR, so write `1 << 3` for this mask rather than using `2 ^ 3` as exponent notation.
7. How can a bitwise operator check whether an integer is even?
The low bit is clear for even integers and set for odd integers, so `(number & 0x0000_0001) == 0` tests for evenness. `number % 2 == 0` is also clear for ordinary arithmetic. Choose the expression that reads better, and benchmark before claiming one is faster in a particular workload.
8. What is the difference between `^` and `**` (exponentiation)?
`^` in Java is bitwise XOR, not exponentiation. `2 ^ 3` returns `1` (`10` XOR `11` is `01`). For exponentiation, use `Math.pow(2, 3)`, which returns `8.0`.
9. What happens when you shift by more than 31 bits on an int?
Java uses only the low 5 bits of an `int` shift distance and the low 6 bits of a `long` shift distance. Therefore, `int x = 7; x << 32` has the same result as `x << 0`, which is `7`.
10. How do you set a specific bit to 1 in a number?
Use OR with a mask that has the target bit set. For example, `value | 0x0000_0008` sets bit 3 in an `int` and leaves the other bits unchanged.
11. How do you clear (set to 0) a specific bit in a number?
Use AND with the complement of the target mask. For bit 3 of an `int`, `value & ~0x0000_0008` clears that bit and preserves the others.
12. What is sign extension with `>>` on negative numbers?
Signed right shift (`>>`) copies the sign bit on the left. For `-8 >> 1`, the result is `-4`. Unsigned shift (`>>>`) fills from the left with zeroes, regardless of the original sign.
13. What is the result of `5 << 3` in Java?
`5 << 3` is `40`: the bits move left three positions. Ordinary `int` and `long` arithmetic wraps when the result exceeds the type's range; the shifted result keeps the low 32 or 64 bits.
14. How does bitwise XOR differ from bitwise OR?
XOR returns `1` when the bits differ: `1 ^ 0 = 1`, `1 ^ 1 = 0`, and `0 ^ 0 = 0`. OR returns `1` when either bit is `1`: `1 | 0 = 1` and `1 | 1 = 1`. For example, `1010 ^ 1100 = 0110`, while `1010 | 1100 = 1110`.
15. What is the complement operator and what does `~5` produce?
The bitwise complement (`~`) flips every bit of its operand. For a 32-bit `int`, `~5` produces `-6` in two's complement representation.
16. What is the unsigned right shift result for `-1 >>> 1`?
`-1 >>> 1` is `2147483647` (`Integer.MAX_VALUE`). In 32-bit two's complement, `-1` has every bit set. The unsigned shift fills the high bit with zero, leaving the positive value `01111111111111111111111111111111`.
17. How do you toggle a specific bit in a number?
Use XOR with a mask that has only the target bit set. For bit 3 of an `int`, `value ^ 0x0000_0008` toggles that bit. Applying the same mask again restores the original value.
18. What is the difference between `1 << 31` and `(1L << 31)`?
`1 << 31` is an `int` expression with the high bit set, represented as `0x8000_0000` or `Integer.MIN_VALUE` (`-2147483648`). `1L << 31` is a `long` with value `2147483648L`, represented by `0x0000_0000_8000_0000L`. The shift does not overflow the `int` expression; its 32-bit result is negative when interpreted as a signed number.
19. How do you count the number of set bits (population count) in Java?
Use `Integer.bitCount(n)` or `Long.bitCount(n)`. For example, `Integer.bitCount(0b10110011)` returns `5`. Prefer the library method over writing a counting loop unless a measured requirement calls for a different implementation.
20. What is the difference between `>>>` and `>>` when shifting negative numbers?
For negative numbers, `>>` copies the sign bit and `>>>` fills with zeroes. For `-4 >> 1` the result is `-2`; for `-4 >>> 1` it is `2147483646`. Use `>>>` when zero-fill is required by the bit layout. For the unsigned numeric interpretation, convert with `Integer.toUnsignedLong`.

Further Reading

Conclusion

Bitwise operators are useful for flag fields and binary layouts where the position of each bit is part of the format. Give flags distinct values, use a mask that matches the field width, and make sign-extension or zero-fill behavior explicit.

For ordinary arithmetic, use the expression that makes intent clear. Measure before claiming a bitwise rewrite improves performance. Use Java’s JCA APIs and providers for cryptographic operations instead of implementing those algorithms with bitwise code.

These operators complement arithmetic operators when a value’s bit layout matters. For enum-backed flags, see Java Enums and Flag Patterns.

Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals