Concept Flow - Unary operators
Start
Apply unary operator
Evaluate expression
Update variable if needed
Use result
End
Unary operators take one value, change or use it, then produce a result or update the variable.
int x = 5; int y = ++x; int z = x--; System.out.println(x + "," + y + "," + z);
| Step | Expression | Variable x | Variable y | Variable z | Action | Output |
|---|---|---|---|---|---|---|
| 1 | int x = 5; | 5 | - | - | Initialize x to 5 | - |
| 2 | int y = ++x; | 6 | 6 | - | Prefix ++ increments x to 6, then y = 6 | - |
| 3 | int z = x--; | 5 | 6 | 6 | Postfix -- assigns z = 6, then decrements x to 5 | - |
| 4 | System.out.println(x + "," + y + "," + z); | 5 | 6 | 6 | Print values of x, y, z | 5,6,6 |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|---|
| x | - | 5 | 6 | 5 | 5 |
| y | - | - | 6 | 6 | 6 |
| z | - | - | - | 6 | 6 |
Unary operators use one operand. Prefix ++ or -- changes value before use. Postfix ++ or -- uses value then changes it. Common unary operators: ++, --, +, -, ! They can update variables or produce new values.