Why conditional statements are needed in Java - Performance Analysis
We want to see how the time a program takes changes when it uses conditional statements.
We ask: Does choosing different paths affect how long the program runs?
Analyze the time complexity of the following code snippet.
int example(int n) {
if (n > 0) {
return n * 2;
} else {
return -n;
}
}
This code checks if a number is positive and returns a value based on that check.
Look for loops or repeated steps.
- Primary operation: A single if-else check.
- How many times: Exactly once per call.
The program does the same amount of work no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check and 1 calculation |
| 100 | 1 check and 1 calculation |
| 1000 | 1 check and 1 calculation |
Pattern observation: The work stays the same no matter how big the input is.
Time Complexity: O(1)
This means the program takes the same short time no matter the input size.
[X] Wrong: "Conditional statements make the program slower as input grows."
[OK] Correct: The condition is checked once, so it does not slow down the program as input gets bigger.
Understanding how conditions affect time helps you explain your code clearly and shows you know how programs behave with different inputs.
"What if we added a loop inside the if statement? How would the time complexity change?"