Unary operators in Java - Time & Space Complexity
Unary operators perform simple actions on a single value. We want to see how fast these actions run as the input changes.
How does the time to run unary operations grow when we use them in code?
Analyze the time complexity of the following code snippet.
int x = 5;
int y = ++x; // pre-increment
int z = y--; // post-decrement
boolean b = !false; // logical NOT
int neg = -z; // unary minus
This code uses several unary operators on simple variables.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Each unary operator acts once on a single value.
- How many times: Each operation runs exactly one time.
Each unary operation takes the same short time no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 4 |
| 100 | 4 |
| 1000 | 4 |
Pattern observation: The number of operations stays the same even if input size grows.
Time Complexity: O(1)
This means the time to run unary operators does not change with input size; it is constant.
[X] Wrong: "Unary operators take longer if the number is bigger or smaller."
[OK] Correct: Unary operators work on one value instantly, no matter its size.
Understanding that simple operations like unary operators run in constant time helps you explain code efficiency clearly and confidently.
"What if we applied unary operators inside a loop running n times? How would the time complexity change?"