0
0
Javaprogramming~5 mins

If–else statement in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If-else statement
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Whether the input is small or large, the program only does one check.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter what number you give it.

Common Mistake

[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.

Interview Connect

Understanding that simple decisions like if-else run in constant time helps you explain how your code behaves clearly and confidently.

Self-Check

"What if we added a loop inside the if or else block? How would the time complexity change?"