Sub topic 6
Unary Operators and Prefix versus Postfix
A unary operator works on one operand. An operand is the value or variable an operator acts on. For example, in -5, the operator - acts on the operand 5.
An expression is a piece of code that produces a value. The expression -5 produces the value negative five.
Common unary operators
| Operator | What it does | Example |
|---|---|---|
| `+` | Gives a numeric value without changing its sign | `+5` produces `5` |
| `-` | Reverses the sign of a numeric value | `-5` produces `-5` |
| `!` | Reverses a boolean value | `!true` produces `false` |
| `++` | Increases a variable by one | `count++` |
| `--` | Decreases a variable by one | `count--` |
A boolean value is either true or false. The ! operator is often read as “not.”
The +, -, and ! operators produce values; they do not change their operands. In contrast, ++ and -- change a variable. A variable is a named place where a program stores a value.
Prefix and postfix
You can place ++ or -- before or after a variable.
- Prefix means the operator comes before the variable, as in
++count. The expression produces the new value. - Postfix means the operator comes after the variable, as in
count++. The expression produces the old value.
Both forms change the variable. The difference matters when you use the value that the expression produces.
Worked example
Save this program as Main.java, then compile and run it:
public class Main {
public static void main(String[] args) {
int count = 3;
int before = count++;
int after = ++count;
int beforeDown = count--;
int afterDown = --count;
System.out.println(before); // 3
System.out.println(after); // 5
System.out.println(beforeDown); // 5
System.out.println(afterDown); // 3
System.out.println(count); // 3
}
}The = operator stores each expression’s result in the variable on its left. Follow the changes to count one line at a time:
| Expression | Value produced | `count` afterward |
|---|---|---|
| `count++` | `3`, the old value | `4` |
| `++count` | `5`, the new value | `5` |
| `count--` | `5`, the old value | `4` |
| `--count` | `3`, the new value | `3` |
When the result is not used, prefix and postfix have the same effect. For example, both count++; and ++count; increase count by one.
Practice
Exercise
If int n = 8;, what are a, b, and n after int a = n--; followed by int b = ++n;?
Show answer
a is 8, b is 8, and n is 8. The postfix decrement produces 8 and changes n to 7; the prefix increment changes it back to 8 and produces 8.
Exercise
If boolean ready = true;, what value does !ready produce? Does it change ready?
Show answer
It produces false. It does not change ready, which remains true.