← Back to Core Java Course | Chapter 14: Advanced Topics | Lesson 4 of 6

Java Bitwise Operations Advanced

Bitwise AND and OR

Bitwise AND (&) sets each output bit only where both operands have a 1, and bitwise OR (|) sets each output bit where either operand has a 1 — both operate independently on every bit position.

Example: Bitwise AND and OR

java
public class Main {
	public static void main(String[] args) {
		System.out.println(5 & 3); // AND: 1
		System.out.println(5 | 3); // OR: 7
	}
}

Bitwise XOR and Complement

Bitwise XOR (^) sets each output bit where exactly one operand has a 1 (but not both), and bitwise complement (~) flips every bit in a single value, turning each 0 into 1 and vice versa.

Example: Bitwise XOR and Complement

java
public class Main {
	public static void main(String[] args) {
		System.out.println(5 ^ 3); // XOR: 6
		System.out.println(~5); // complement: -6
	}
}

Left Shift Operator

Left shift (<<) moves all bits toward the higher end, filling vacated positions with zeros — this is equivalent to multiplying by a power of two for each position shifted.

Example: Left Shift Operator

java
public class Main {
	public static void main(String[] args) {
		System.out.println(3 << 2); // 3 * 2^2 = 12
	}
}

Signed Right Shift Operator

Signed right shift (>>) moves bits toward the lower end while preserving the sign bit, so shifting a negative number keeps it negative — equivalent to dividing by a power of two while keeping sign correct.

Example: Signed Right Shift Operator

java
public class Main {
	public static void main(String[] args) {
		System.out.println(-8 >> 1); // sign preserved: -4
	}
}

Unsigned Right Shift Operator

Unsigned right shift (>>>) always fills vacated high-order bits with zero regardless of sign, which matters specifically when working with a negative number where you want a positive result instead of sign-preserving behavior.

Example: Unsigned Right Shift Operator

java
public class Main {
	public static void main(String[] args) {
		System.out.println(-8 >>> 1); // fills with zero, ignores sign
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.