Bitwise operators and flags
Set, clear, test and shift bits — the idiom behind permission flags and fast maths.
Open this lesson in the learning hubKey points
&is AND,|is OR,^is XOR, and~flips every bit.- Set with
x |= FLAG, clear withx &= ~FLAG, test with(x & FLAG) != 0. &and|on booleans do not short-circuit, unlike&&and||. Do not mix them up.<<doubles,>>halves keeping the sign, and>>>shifts in zeros.n & 1reads the lowest bit, which is the fastest even/odd test there is.- Print the bits with
Integer.toBinaryString— and in new code prefer anEnumSetover a flags int.
Example
public class Main {
static final int READ = 1;
static final int WRITE = 2;
static final int EXEC = 4;
static String bits(int n) {
return String.format("%4s", Integer.toBinaryString(n)).replace(' ', '0');
}
public static void main(String[] args) {
int perms = READ | EXEC;
System.out.println("perms = " + bits(perms) + " (" + perms + ")");
System.out.println("has READ ? " + ((perms & READ) != 0));
System.out.println("has WRITE? " + ((perms & WRITE) != 0));
perms |= WRITE;
System.out.println("set WRITE = " + bits(perms));
perms &= ~EXEC;
System.out.println("clear EXEC = " + bits(perms));
System.out.println("toggle READ= " + bits(perms ^ READ));
System.out.println("1 << 5 = " + (1 << 5) + " (times 32)");
System.out.println("40 >> 2 = " + (40 >> 2) + " (divided by 4)");
System.out.println("-8 >> 1 = " + (-8 >> 1) + " keeps the sign, -8 >>> 28 = " + (-8 >>> 28));
System.out.println("13 is odd? " + ((13 & 1) == 1));
System.out.println("& is not &&: it never short-circuits");
}
}
OR to set, AND-NOT to clear, AND to test — all in a single int.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.