Ternary operator in Java - Time & Space Complexity
Let's see how using the ternary operator affects how long a program takes to run.
We want to know if it changes the speed compared to other ways of choosing between two values.
Analyze the time complexity of the following code snippet.
int max = (a > b) ? a : b;
System.out.println(max);
This code picks the bigger of two numbers using the ternary operator and prints it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single comparison between two numbers.
- How many times: Exactly once per execution.
Since the ternary operator does one check, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run this code stays constant, no matter the input size.
[X] Wrong: "Using the ternary operator makes the program slower because it adds extra checks."
[OK] Correct: The ternary operator does just one simple check, same as an if-else, so it does not slow down the program.
Understanding that simple choices like the ternary operator run in constant time helps you explain your code clearly and confidently.
"What if we used the ternary operator inside a loop that runs n times? How would the time complexity change?"