Static methods in interfaces in Java - Time & Space Complexity
We want to understand how the time it takes to run static methods in interfaces changes as input size grows.
How does the work inside these methods scale when given bigger inputs?
Analyze the time complexity of the following code snippet.
public interface Calculator {
static int sumArray(int[] numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
}
This static method sums all numbers in an array passed to it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-each loop that adds each number to a total.
- How many times: Once for every element in the input array.
As the array gets bigger, the method does more additions, one per element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Static methods in interfaces always run instantly or in constant time."
[OK] Correct: Static methods can have loops or other work that depends on input size, so their time can grow with input.
Understanding how static methods in interfaces behave helps you explain performance clearly and shows you know how Java features work under the hood.
"What if the static method called another method inside that also loops over the array? How would the time complexity change?"