0
0
Javaprogramming~5 mins

Nested if statements in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested if statements
O(1)
Understanding Time Complexity

We want to see how the time it takes to run nested if statements changes as the input grows.

Specifically, we ask: Does adding more conditions inside each other make the program slower?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


int checkNumber(int n) {
  if (n > 0) {
    if (n % 2 == 0) {
      return 1;
    } else {
      return 2;
    }
  } else {
    return 0;
  }
}
    

This code checks if a number is positive and then if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here.
  • How many times: Each condition is checked only once per call.
How Execution Grows With Input

Since the code only checks conditions once, the time does not grow with input size.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

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

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays constant, no matter how big the input is.

Common Mistake

[X] Wrong: "Nested if statements always make the program slower as input grows."

[OK] Correct: Nested ifs just check conditions once each; they don't repeat work based on input size.

Interview Connect

Understanding that nested ifs do not increase time with input size helps you explain code efficiency clearly and confidently.

Self-Check

"What if we added a loop inside the nested if statements? How would the time complexity change?"