Java Bitwise Operators
In this page:
Bitwise AND and OR
Bitwise & and | act on the individual binary bits of a number rather than its value as a whole: & keeps a bit only where both operands have a 1, while | sets a bit wherever either operand has a 1.
Example: Bitwise AND and OR
public class Main {
public static void main(String[] args) {
int a = 6; // 110
int b = 3; // 011
System.out.println(a & b); // 2 - 1 only where both have a 1
System.out.println(a | b); // 7 - 1 where either has a 1
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise XOR (^)
^ (XOR) sets each output bit to 1 only when the two input bits differ -- a classic use is swapping two integers without a temporary variable, or toggling specific flag bits on and off.
Example: Bitwise XOR (^)
public class Main {
public static void main(String[] args) {
int a = 5, b = 3;
System.out.println(a ^ b); // 1 - set where bits differ
a ^= b; b ^= a; a ^= b; // classic swap without a temp variable
System.out.println(a + " " + b);
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise Complement ()
The bitwise complement operator ~ flips every single bit in a number's binary representation, which for signed integers is mathematically equivalent to computing -(x + 1).
Example: Bitwise Complement ()
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(~x); // -6, equivalent to -(x + 1)
}
}
Login to try C/C++/Java/PHP code in the editor
Shift Operators
<< shifts all bits left, filling with zeros on the right, which doubles the value for each position shifted; >> shifts bits right, which halves the value (rounding toward negative infinity) and is much faster than an actual division for powers of two.
Example: Shift Operators
public class Main {
public static void main(String[] args) {
int x = 4;
System.out.println(x << 1); // 8 - doubles the value
System.out.println(x >> 1); // 2 - halves the value
}
}
Login to try C/C++/Java/PHP code in the editor
Bitwise Compound Assignment
Combining bitwise operations with assignment (&=, |=, ^=) lets you update flag-style variables in place, a common pattern when a single int is used to pack several true/false settings into individual bits.
Example: Bitwise Compound Assignment
public class Main {
public static void main(String[] args) {
int flags = 0b0100;
flags |= 0b0001; // sets a bit in place
flags &= 0b0111; // clears a bit in place
System.out.println(flags);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: