0
0
Javaprogramming~15 mins

Method parameters in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: Method parameters
O(n)
menu_bookUnderstanding Time Complexity

We want to see how the time a method takes changes when we give it different inputs.

How does the method's work grow as the input size changes?

code_blocksScenario Under Consideration

Analyze the time complexity of the following code snippet.

public void printNumbers(int n) {
    for (int i = 0; i < n; i++) {
        System.out.println(i);
    }
}

This method prints numbers from 0 up to n-1, one by one.

repeatIdentify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that prints numbers.
  • How many times: It runs exactly n times, once for each number.
search_insightsHow Execution Grows With Input

As n grows, the method prints more numbers, so it takes more time.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: The work grows directly with n; doubling n doubles the work.

cards_stackFinal Time Complexity

Time Complexity: O(n)

This means the time grows in a straight line with the input size.

chat_errorCommon Mistake

[X] Wrong: "The method always takes the same time no matter the input."

[OK] Correct: The method prints once for each number up to n, so bigger n means more work.

business_centerInterview Connect

Understanding how method parameters affect time helps you explain your code clearly and think about efficiency.

psychology_altSelf-Check

"What if the method printed numbers only up to n/2? How would the time complexity change?"