Sub topic 13
Bitwise and Non-Short-Circuit Boolean Operators
Java uses some of the same symbols for two different jobs. With whole numbers, &, |, and ^ work on individual bits. With Boolean values, they combine true and false values.
This chapter assumes you know Java variables, basic data types, and how to run a simple Java program. You should also know that && and || can skip their right-hand expressions.
Bits and binary numbers
A bit is a single digit that is either 0 or 1. Computers store whole numbers as patterns of bits. A binary number is a number written with only 0 and 1.
Java uses the prefix 0b for a binary number. For example, 0b1010 is the same value as decimal 10. Each position represents a power of two:
| Binary position | 8 | 4 | 2 | 1 |
|---|---|---|---|---|
| Bits in `0b1010` | 1 | 0 | 1 | 0 |
The 1 bits select 8 and 2, so the value is 10.
An int stores a signed whole number using 32 bits. The examples below show only the last four bits when that is enough to see the result.
Working on bits
A bitwise operator compares bits in the same positions of whole-number values. The &, |, and ^ operators each take two operands, or values they work on.
| First bit | Second bit | `&` AND | ` | ` OR | `^` XOR |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | |
| 0 | 1 | 0 | 1 | 1 | |
| 1 | 0 | 0 | 1 | 1 | |
| 1 | 1 | 1 | 1 | 0 |
- AND (
&) gives1only when both bits are1. - OR (
|) gives1when either bit or both bits are1. - XOR (
^) gives1when exactly one bit is1. XOR means “exclusive OR.” The^symbol does not mean “raise to a power” in Java.
For example, 0b1010 & 0b0010 gives 0b0010, or 2. Only the bit in the 2 position is 1 in both values.
The bitwise NOT operator, ~, takes one whole-number operand. It flips every bit: 0 becomes 1, and 1 becomes 0.
Using a mask to manage flags
A flag is a bit used to represent a yes-or-no setting. A mask is a number whose 1 bits mark the positions you want to check or change.
Suppose a program stores four settings in an int. The value 0b1010 has the 8 and 2 flags turned on.
To check the 2 flag, use 0b0010 as a mask:
(flags & 0b0010) != 0
The parentheses are important. They make Java perform the bitwise AND before comparing the result with zero. The expression is true if the selected bit is on.
You can also change flags without changing the other bits:
- Turn on selected bits with
|=. - Turn off selected bits with
&= ~. - Toggle selected bits with
^=. To toggle a bit means to change0to1or1to0.
These are compound assignment operators. For an int, flags |= mask sets flags to the result of flags | mask.
Worked example
Save this program as BitwiseDemo.java, then compile and run it with javac BitwiseDemo.java and java BitwiseDemo.
public class BitwiseDemo {
public static void main(String[] args) {
int flags = 0b1010;
int mask = 0b0010;
System.out.println("AND: " + (flags & mask));
System.out.println("OR: " + (flags | mask));
System.out.println("XOR: " + (flags ^ mask));
System.out.println("NOT flags: " + (~flags));
System.out.println("2 flag on: " + ((flags & mask) != 0));
flags |= 0b0001;
System.out.println("After turning on 1: " + flags);
flags &= ~0b0010;
System.out.println("After turning off 2: " + flags);
flags ^= 0b1000;
System.out.println("After toggling 8: " + flags);
System.out.println("false & check: " + (false & check()));
System.out.println("false && check: " + (false && check()));
System.out.println("true | check: " + (true | check()));
System.out.println("true || check: " + (true || check()));
System.out.println("true ^ check: " + (true ^ check()));
}
static boolean check() {
System.out.println("check ran");
return true;
}
}The output is:
AND: 2
OR: 10
XOR: 8
NOT flags: -11
2 flag on: true
After turning on 1: 11
After turning off 2: 9
After toggling 8: 1
check ran
false & check: false
false && check: false
check ran
true | check: true
true || check: true
check ran
true ^ check: falseThe flag changes start at 0b1010, or 10. Turning on the 1 bit gives 0b1011, or 11. Turning off the 2 bit gives 0b1001, or 9. Finally, toggling the 8 bit gives 0b0001, or 1.
Checking several flags
A mask can contain more than one 1 bit. These two checks answer different questions:
(flags & mask) != 0asks whether at least one selected bit is on.(flags & mask) == maskasks whether all selected bits are on.
For example, if flags is 0b0010 and mask is 0b1010, the first check is true: the 2 bit is on. The second is false: the 8 bit is off.
A zero mask is a special case. With mask equal to 0, the “at least one” check is always false, while the “all” check is always true.
Boolean operators that do not skip
A Boolean value is either true or false. When both operands are Boolean values, &, |, and ^ return a Boolean result instead of working on bits.
Their rules match the bit table: & means both, | means either or both, and ^ means exactly one. Unlike && and ||, these operators do not short-circuit. Short-circuiting means skipping the right operand when the left operand already determines the result.
In the program, check() is a method: a named set of instructions. Calling it prints check ran and returns true. Printing is a side effect, or an action besides producing a value.
false & check()callscheck(), even though the result must befalse.false && check()skipscheck().true | check()callscheck(), even though the result must betrue.true || check()skipscheck().true ^ check()callscheck()and givesfalse, because both values aretrue.
Java evaluates the left operand first. If evaluating it fails with an exception, the right operand does not run.
Choosing the right operator
Use && and || for most Boolean conditions. They can avoid unnecessary work and can protect an operation that is only safe in some cases.
For example, name != null && !name.isEmpty() checks that name is not null before calling isEmpty(). The value null means there is no object to call the method on. If you replace && with &, Java still tries to call isEmpty() when name is null, causing an exception.
Use Boolean & or | when you deliberately need both sides evaluated. Be careful if either side changes a value, prints, or can fail.
Practice
Exercise
What are the decimal results of 0b1100 & 0b0101 and 0b1100 ^ 0b0101?
Show answer
AND gives 0b0100, or 4. XOR gives 0b1001, or 9.
Exercise
If flags is 0b0010 and mask is 0b1010, are all masked bits on?
Show answer
No. (flags & mask) == mask is false because the 8 bit is off.
Exercise
If check() prints a message and returns true, does false & check() print the message? Does false && check()?
Show answer
The first expression prints it because & evaluates the right side. The second skips the call because && short-circuits.