Java
Module 3: Java OperatorsBeginner20 min read

Bitwise, Shift, Ternary & Operator Precedence

Use bitwise AND/OR/XOR, signed and unsigned shifts (<<, >>, >>>), the ternary operator (?:), and operator precedence rules.

Key Takeaways & Core Concepts
  • `&` (Bitwise AND): 1 only if both bits are 1. Useful for bitmasking ((num & 1) == 0 checks even numbers).
  • `|` (Bitwise OR): 1 if either bit is 1. Useful for combining permission flags.
  • `^` (Bitwise XOR): 1 if bits differ. Property: a ^ a == 0 and a ^ 0 == a.
  • `~` (Bitwise Complement): Flips every bit (~n == -(n + 1)).

Introduction

Bitwise and shift operators manipulate individual bits inside integer types (byte, short, int, long), which is foundational for permissions flags, hashing, compression, and low-level algorithms.

Bitwise Parity, Shifts & Ternary
1public class Main {
2 public static void main(String[] args) {
3 int num = 12;
4 String parity = ((num & 1) == 0) ? "Even" : "Odd";
5 System.out.println(num + " is " + parity);
6 System.out.println("12 << 2 = " + (num << 2));
7 System.out.println("12 >> 1 = " + (num >> 1));
8 }
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: `num << 2` shifts bits left by 2 positions, equivalent to `12 * 4 = 48`.

Bitwise & Shift Operators

  • `&` (Bitwise AND): 1 only if both bits are 1. Useful for bitmasking ((num & 1) == 0 checks even numbers).
  • `|` (Bitwise OR): 1 if either bit is 1. Useful for combining permission flags.
  • `^` (Bitwise XOR): 1 if bits differ. Property: a ^ a == 0 and a ^ 0 == a.
  • `~` (Bitwise Complement): Flips every bit (~n == -(n + 1)).
  • `<<` (Left Shift): Shifts bits left, filling zeros on the right (multiplies by 2^n).
  • `>>` (Signed Right Shift): Preserves the sign bit (divides by 2^n).
  • `>>>` (Unsigned Right Shift): Shifts 0 into the sign bit regardless of whether the number is negative.

Ternary Operator

condition ? exprIfTrue : exprIfFalse evaluates condition first and returns one of the two expressions. Unlike if-else, it is an expression that produces a value.

Precedence & Associativity

Unary > Multiplicative (*, /, %) > Additive (+, -) > Shift > Relational > Equality > Bitwise > Logical > Ternary > Assignment. When in doubt, add parentheses () for readability.

Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)