Java Operators
Symbols that perform actions on values.
Arithmetic operators
| Op | Meaning | Example | Result |
|---|---|---|---|
+ | Add | 5 + 3 | 8 |
- | Subtract | 5 - 3 | 2 |
* | Multiply | 5 * 3 | 15 |
/ | Divide | 10 / 3 | 3 (int division!) |
% | Modulo (remainder) | 10 % 3 | 1 |
Integer division gotcha
10 / 3 with two ints gives 3, not 3.33. To get a decimal result, at least one operand must be a double: 10.0 / 3 gives 3.333....
Comparison operators
Return boolean:
Comparisons
int a = 5, b = 10; System.out.println(a == b); // false (equal) System.out.println(a != b); // true (not equal) System.out.println(a < b); // true System.out.println(a <= b); // true System.out.println(a > b); // false System.out.println(a >= b); // false
String comparison: use .equals(), not ==
For strings,
== compares references (memory addresses), not content. Always use .equals():
String a = "hello"; String b = new String("hello"); System.out.println(a == b); // false System.out.println(a.equals(b)); // true
Logical operators
Logical
boolean a = true, b = false; System.out.println(a && b); // false (AND) System.out.println(a || b); // true (OR) System.out.println(!a); // false (NOT)
Short-circuit: && and || stop evaluating as soon as the result is determined. false && expensiveCheck() never calls expensiveCheck().
Assignment operators
Compound assignment
int x = 10; x += 5; // x = x + 5 → 15 x -= 3; // x = x - 3 → 12 x *= 2; // x = x * 2 → 24 x /= 4; // x = x / 4 → 6 x %= 4; // x = x % 4 → 2
Increment / decrement
++ and --
int i = 5; i++; // post-increment: i is now 6 ++i; // pre-increment: i is now 7 int a = 5; int b = a++; // b = 5, then a = 6 int c = ++a; // a = 7, then c = 7
Ternary operator
Compact if/else: condition ? valueIfTrue : valueIfFalse
Ternary
int age = 17; String status = (age >= 18) ? "adult" : "minor"; System.out.println(status); // "minor"
Bitwise operators
Operate on bits. Used in low-level code, flags, performance-critical paths.
| Op | Meaning |
|---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise XOR |
~ | Bitwise NOT |
<< | Left shift (× 2) |
>> | Right shift (÷ 2) |