Operators & Expressions
BeginnerFrom arithmetic and bitwise to ternary and instanceof — learn every operator Java offers and how precedence determines evaluation order.
Overview
Java operators fall into six groups: arithmetic, relational, logical, bitwise/shift, assignment, and miscellaneous. Understanding short-circuit evaluation (&&, ||) avoids null checks and is essential for writing safe conditions. Bitwise and shift operators are staples of competitive programming and low-level Java (flags, permissions, hashCode implementations). Operator precedence surprises even experienced developers — when in doubt, add parentheses.
Arithmetic & Relational Operators
The five arithmetic operators (+, −, *, /, %) work on numeric types. Integer division truncates toward zero: 7/2 = 3, not 3.5. The modulo operator works on negative numbers too: -7 % 3 = -1 in Java (sign follows the dividend).
Relational operators (==, !=, <, >, <=, >=) return boolean. For primitives == compares values; for objects it compares references (memory addresses). Always use .equals() to compare object content.
public class ArithmeticDemo {
public static void main(String[] args) {
int a = 7, b = 2;
System.out.println(a + b); // 9
System.out.println(a - b); // 5
System.out.println(a * b); // 14
System.out.println(a / b); // 3 (integer division — truncates)
System.out.println(a % b); // 1 (remainder)
// Cast to double for real division
System.out.println((double) a / b); // 3.5
// Negative modulo: sign follows dividend
System.out.println(-7 % 3); // -1
System.out.println(7 % -3); // 1
// Pre vs post increment
int x = 5;
System.out.println(x++); // 5 (post: use then increment)
System.out.println(++x); // 7 (pre: increment then use)
// Overflow wraps silently for int
System.out.println(Integer.MAX_VALUE + 1); // -2147483648
// Use Math.addExact() to throw on overflow
// Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticException
}
}Logical & Short-Circuit Operators
&& (AND) and || (OR) are short-circuit operators: the right-hand side is only evaluated if necessary. && stops at the first false; || stops at the first true. This prevents NullPointerExceptions in chained null checks.
& and | are non-short-circuit (bitwise AND/OR on integers, but also work on booleans without short-circuiting). Use && and || for conditions — the short-circuit behaviour is almost always what you want.
! is logical NOT. ^ is XOR (returns true only when operands differ).
public class LogicalDemo {
static boolean check(String s) {
System.out.println("check() called");
return s.length() > 3;
}
public static void main(String[] args) {
String name = null;
// Short-circuit && : right side NOT evaluated when left is false
if (name != null && name.length() > 0) {
System.out.println("Safe");
} else {
System.out.println("Name is null — no NPE!");
}
// Short-circuit || : right side NOT evaluated when left is true
boolean flag = true;
if (flag || check("hello")) {
// check() is never called
System.out.println("Short-circuited OR");
}
// Ternary operator: condition ? valueIfTrue : valueIfFalse
int score = 85;
String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
System.out.println(grade); // B
// XOR: true only when operands differ
System.out.println(true ^ false); // true
System.out.println(true ^ true); // false
}
}Bitwise & Shift Operators
Bitwise operators work on the binary representation of integers:
& (AND) — bit is 1 only when both are 1: 6 & 4 = 4 (110 & 100 = 100) | (OR) — bit is 1 when either is 1: 6 | 4 = 6 ^ (XOR) — bit is 1 when they differ: 6 ^ 4 = 2 ~ (NOT) — flips all bits: ~6 = -7 (two's complement)
Shift operators: << left shift (multiply by 2ⁿ), >> signed right shift (divide by 2ⁿ, preserves sign), >>> unsigned right shift (fills with 0, used in hashCode).
Common patterns: n & 1 checks odd/even, n & (n-1) clears lowest set bit, n | (1<<k) sets bit k.
public class BitwiseDemo {
public static void main(String[] args) {
int a = 6; // 0110
int b = 4; // 0100
System.out.println(a & b); // 4 (0100)
System.out.println(a | b); // 6 (0110)
System.out.println(a ^ b); // 2 (0010)
System.out.println(~a); // -7 (flip all bits)
// Shift operators
System.out.println(1 << 3); // 8 (left shift = *8)
System.out.println(16 >> 2); // 4 (right shift = /4)
System.out.println(-1 >>> 1); // Integer.MAX_VALUE (unsigned)
// Practical tricks
int n = 7;
System.out.println((n & 1) == 1 ? "odd" : "even"); // odd
// Swap without temp variable using XOR
int x = 10, y = 20;
x ^= y; y ^= x; x ^= y;
System.out.println(x + ", " + y); // 20, 10
// Count set bits (Integer.bitCount is more readable in prod)
int count = 0;
for (int num = 13; num > 0; num >>= 1) count += num & 1;
System.out.println("Set bits in 13: " + count); // 3
}
}Key Points to Remember
- Integer division truncates toward zero: 7/2 = 3; cast to double for real division
- Use && and || (short-circuit) for conditions — prevents NPE on chained null checks
- For object comparison, == tests reference equality; use .equals() for content equality
- Integer overflow wraps silently; use Math.addExact() to throw ArithmeticException
- <<n multiplies by 2ⁿ; >>n divides by 2ⁿ; >>>n is unsigned (fills with 0)
- n & 1 checks odd/even; n & (n-1) clears the lowest set bit — staples of bit manipulation
Practice Operators & Expressions in the Playground
Run and modify code directly in your browser - no setup needed.
Interview Questions
Sign in to ask AriaWhat is the difference between & and && in Java?
How do you check if a number is a power of 2 using bitwise operators?
What is short-circuit evaluation and why is it useful?
What is the result of Integer.MAX_VALUE + 1 in Java?
How would you swap two integers without a temp variable?
Ask Aria about Operators & Expressions
Your personal AI tutor — ask anything about this concept