Method parameters in Java - Time & Space 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?
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.
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.
As n grows, the method prints more numbers, so it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time grows in a straight line with the input size.
[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.
Understanding how method parameters affect time helps you explain your code clearly and think about efficiency.
"What if the method printed numbers only up to n/2? How would the time complexity change?"
