If–else statement in Java - Time & Space Complexity
We want to see how the time to run an if-else statement changes as the input changes.
Does the choice inside the if-else affect how long the program takes?
Analyze the time complexity of the following code snippet.
int checkNumber(int n) {
if (n > 0) {
return 1;
} else {
return -1;
}
}
This code checks if a number is positive or not and returns a value accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else check.
- How many times: Exactly once per call, no loops or repeated steps.
Whether the input is small or large, the program only does one check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter what number you give it.
[X] Wrong: "If-else statements take longer when the number is bigger."
[OK] Correct: The if-else only checks once, so the size of the number does not change how long it takes.
Understanding that simple decisions like if-else run in constant time helps you explain how your code behaves clearly and confidently.
"What if we added a loop inside the if or else block? How would the time complexity change?"