Unary Operators
1. What Unary Means (beginner)
Unary = one operand. ++, --, +, -, !, ~. Most-used: ++/-- in loops. Most-confusing: i++ vs ++i.
2. Post vs Pre (the #1 confusion)
| Form | Meaning | Example (x=5) |
|---|---|---|
x++ (post) |
use first, then +1 | y=x++; → y=5, x=6 |
++x (pre) |
+1 first, then use | y=++x; → x=6, y=6 |
x-- / --x |
same for minus | y=x--; → y=5, x=4 |
-x / +x |
sign flip / no-op | -5 → -5 |
! |
boolean NOT | !true → false |
~ |
bitwise NOT (flips bits) | ~5 → -6 |
3. Code — See the Difference
public class Unary {
public static void main(String[] args) {
int x = 5;
System.out.println(x++); // 5 (prints, then x=6)
System.out.println(x); // 6
System.out.println(++x); // 7 (first x=7, then prints)
int i = 0;
while (i < 3) { System.out.print(i++ + " "); } // 0 1 2 (classic loop use)
System.out.println(!true); // false
}
}
4. Traps
x = x++stays same! (post saves old, then overwrites). Never write this.i++inwhile(i<3)prints 0 1 2 — favourite output question.!only on boolean:!5is ERROR (unlike C).
5. Exam Points
- Predict output (
x++vs++x) — 5 marks, very frequent. - Loop trace with
i++— 3 marks, frequent.