Chapter 620 min read
Java Operators & Expression Evaluation
A comprehensive guide to mathematical, comparison, bitwise, conditional, and memory operators in Java.
Released1995
Core MottoStrong Typing & Strict Evaluation Rules
CreatorsOracle / Sun Microsystems
1. Arithmetic & Assignment Operators
Arithmetic operators perform basic mathematical calculations on variables and literals.
Assignment operators set or modify variable values, with shorthand compound assignment options.
Basic Arithmetic & The Integer Division Behavior
Standard Math:Addition (+), Subtraction (-), Multiplication (*).
Integer Division (/):When dividing two whole numbers (integers), Java drops the decimal fraction completely (e.g., `10 / 4` equals `2`). To keep decimals, at least one value must be a floating-point type (`10.0 / 4` equals `2.5`).
Modulus (%):Returns the remainder after integer division (e.g., `10 % 3` equals `1`).
Unary Increment (++ / --):Adds or subtracts 1 from a variable.
java
public class ArithmeticExample {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("a + b = " + (a + b)); // 15
System.out.println("a - b = " + (a - b)); // 5
System.out.println("a * b = " + (a * b)); // 50
System.out.println("a / b = " + (a / b)); // 2
System.out.println("a % b = " + (a % b)); // 0
}
}Assignment & Compound Assignment Operators
Simple Assignment (=):Evaluates the right side and assigns the final value to the left variable.
Compound Assignments (+=, -=, *=, /=, %=):Performs an arithmetic operation and updates the variable in place.
Implicit Casting Feature:Compound operators automatically cast the result to the left operand's data type.
java
public class AssignmentExample {
public static void main(String[] args) {
int a = 10;
a += 5; // Equivalent to: a = a + 5 (15)
System.out.println("a += 5: " + a);
a -= 3; // Equivalent to: a = a - 3 (12)
System.out.println("a -= 3: " + a);
a *= 2; // Equivalent to: a = a * 2 (24)
System.out.println("a *= 2: " + a);
a /= 4; // Equivalent to: a = a / 4 (6)
System.out.println("a /= 4: " + a);
a %= 5; // Equivalent to: a = a % 5 (1)
System.out.println("a %= 5: " + a);
}
}2. Relational & Logical Operators
Relational operators compare values and evaluate to a boolean (true or false).
Logical operators combine multiple boolean expressions using AND, OR, and NOT rules.
Relational Operators (Comparisons)
Comparative Operators:`==` (equal to), `!=` (not equal to), `>` (greater than), `<` (less than), `>=` (greater than or equal to), `<=` (less than or equal to).
Boolean Result:Every relational operation evaluates directly to `true` or `false`.
Pitfall Warning:Never confuse `=` (assigning a value) with `==` (comparing two values).
java
public class RelationalExample {
public static void main(String[] args) {
int A = 10, B = 5;
System.out.println("A == B: " + (A == B)); // false
System.out.println("A != B: " + (A != B)); // true
System.out.println("A > B: " + (A > B)); // true
System.out.println("A < B: " + (A < B)); // false
System.out.println("A >= B: " + (A >= B)); // true
System.out.println("A <= B: " + (A <= B)); // false
}
}Logical Operators & Short-Circuiting
Logical AND (&&):Evaluates to `true` only when BOTH operands are true.
Logical OR (||):Evaluates to `true` if AT LEAST ONE operand is true.
Logical NOT (!):Inverts a boolean value (turns true to false, and false to true).
Short-Circuit Evaluation:`&&` skips the right expression if the left side is `false`. `||` skips the right expression if the left side is `true`.
java
public class LogicalExample {
public static void main(String[] args) {
boolean A = true, B = false;
System.out.println("A && B: " + (A && B)); // false
System.out.println("A || B: " + (A || B)); // true
System.out.println("!A: " + (!A)); // false
System.out.println("!B: " + (!B)); // true
}
}3. Bitwise Operators & Binary Manipulation
Bitwise operators perform operations directly at the binary bit level (0s and 1s) on integer data types.
Bitwise Operations & Shift Operators
Bitwise AND (&):Sets bit to 1 if present in both operands.
Bitwise OR (|):Sets bit to 1 if present in either operand.
Bitwise XOR (^):Sets bit to 1 if present in one operand, but not both.
Bitwise Complement (~):Flips every bit (0 becomes 1, 1 becomes 0).
Left Shift (<<):Shifts bits left, filling empty spaces on the right with zeros.
Signed Right Shift (>>):Shifts bits right while preserving the sign bit.
Unsigned Right Shift (>>>):Shifts bits right and fills empty top spaces with zeros regardless of sign.
java
public class BitwiseExample {
public static void main(String[] args) {
int A = 60; // Binary: 0011 1100
int B = 13; // Binary: 0000 1101
System.out.println("A & B: " + (A & B)); // 12 (0000 1100)
System.out.println("A | B: " + (A | B)); // 61 (0011 1101)
System.out.println("A ^ B: " + (A ^ B)); // 49 (0011 0001)
System.out.println("~A: " + (~A)); // -61 (2's complement)
System.out.println("A << 2: " + (A << 2)); // 240 (1111 0000)
System.out.println("A >> 2: " + (A >> 2)); // 15 (0000 1111)
System.out.println("A >>> 2: " + (A >>> 2)); // 15 (0000 1111)
}
}4. Special & Miscellaneous Operators
Java features unique shortcut operators such as the Ternary Conditional operator and the instanceof type-checking operator.
The Ternary Operator (? :)
Compact Decision Tool:Replaces basic `if-else` blocks with a single readable line.
Syntax:`variable = (condition) ? value_if_true : value_if_false;`.
java
public class TernaryExample {
public static void main(String[] args) {
int a = 10;
// If (a == 1) returns 20, otherwise 30
int b = (a == 1) ? 20 : 30;
System.out.println("Value of b is: " + b); // Outputs: 30
b = (a == 10) ? 20 : 30;
System.out.println("Value of b is: " + b); // Outputs: 20
}
}The instanceof Type Operator
Object Type Checking:Checks whether an object reference is an instance of a specific Class or Interface.
Safe Downcasting:Prevents runtime ClassCastException errors by validating inheritance relationships beforehand.
java
class Vehicle {}
public class Car extends Vehicle {
public static void main(String[] args) {
String name = "James";
boolean isString = name instanceof String;
System.out.println("Is 'name' a String? " + isString); // true
Vehicle myCar = new Car();
boolean isCar = myCar instanceof Car;
System.out.println("Is 'myCar' an instance of Car? " + isCar); // true
}
}5. Operator Precedence & Associativity
Precedence determines which operations run first in complex expressions.
Associativity dictates evaluation direction (Left-to-Right or Right-to-Left) when operators share equal priority.
Precedence Priority Order
1.
Parentheses `()` & Postfix `expr++`, `expr--` (Highest Priority)
2.
Unary / Prefix `++expr`, `--expr`, `+`, `-`, `~`, `!`
3.
Multiplicative `*`, `/`, `%`
4.
Additive `+`, `-`
5.
Shift `<<`, `>>`, `>>>`
6.
Relational `<`, `>`, `<=`, `>=`, `instanceof`
7.
Equality `==`, `!=`
8.
Bitwise `&`, `^`, `|`
9.
Logical `&&`, `||`
10.
Ternary `?:`
11.
Assignment `=`, `+=`, `-=`, etc. (Lowest Priority)
Precedence in Action
Parentheses Override:Using `()` forces inner operations to execute ahead of higher-precedence operators.
Associativity Rules:Arithmetic operators evaluate Left-to-Right (`20 / 4 * 2` becomes `5 * 2 = 10`), whereas Assignment operators evaluate Right-to-Left.
java
public class OperatorPrecedenceExample {
public static void main(String[] args) {
int result1 = 10 + 5 * 2; // 5 * 2 = 10, then + 10 = 20
int result2 = (10 + 5) * 2; // (10 + 5) = 15, then * 2 = 30
int result3 = 20 / 4 * 2; // Left-to-right: (20 / 4) = 5, then * 2 = 10
int result4 = 10 - 3 + 2; // Left-to-right: (10 - 3) = 7, then + 2 = 9
System.out.println("10 + 5 * 2 = " + result1);
System.out.println("(10 + 5) * 2 = " + result2);
System.out.println("20 / 4 * 2 = " + result3);
System.out.println("10 - 3 + 2 = " + result4);
}
}Classroom Discussion Starter
Why is it considered good practice to use explicit parentheses even when Java's operator precedence rules already guarantee the correct evaluation order?
Takeaway Goal: Explicit parentheses remove ambiguity for human developers reading the code, prevent subtle calculation bugs during maintenance, and make intent explicit without requiring team members to memorize the entire precedence table.