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.
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
- Sign extension with
>>:-4 >> 1returns-2, not2. Use>>>for logical shift. ^is XOR, not exponentiation:2 ^ 3returns1, not8. UseMath.pow().- Shift distance: A negative or oversized distance is masked by Java. For
int, only the low 5 bits are used; forlong, the low 6 bits are used. The sign of the value being shifted is a separate concern. - Bitwise ops on negative numbers: Results can be counterintuitive. Document assumptions.
- Operand types: Integer bitwise and shift operations use
intorlongoperands;byte,short, andcharvalues are promoted toint. 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
intorlong. - 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
Further Reading
- Arithmetic Operators in Java - Numeric operations that complement bitwise manipulation
- Java Enums and Flag Patterns - Using enums to define type-safe bit flags
- Network Protocol Implementation - Bit-level operations for protocol parsing
- Java SE 27 Java Cryptography Architecture guide - JCA APIs and provider model for cryptographic operations
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.
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 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.