Method declaration in Java - Time & Space Complexity
When we look at a method declaration, we want to understand how the time it takes to run changes as the input changes.
We ask: How does the work inside the method grow when inputs get bigger?
Analyze the time complexity of the following code snippet.
public int sumArray(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
This method adds all numbers in an array and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-each loop that adds each number to sum.
- How many times: Once for each element in the input array.
As the array gets bigger, the method does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items in the array.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "The method takes the same time no matter how big the array is."
[OK] Correct: Because the method must add each number, more numbers mean more work and more time.
Understanding how loops inside methods affect time helps you explain your code clearly and shows you know how programs grow with input.
"What if we changed the method to sum only the first half of the array? How would the time complexity change?"
