Method calling in Java - Time & Space Complexity
When we call a method in Java, it takes some time to run. We want to see how this time changes when the method is called many times.
How does the total work grow as we call the method more?
Analyze the time complexity of the following code snippet.
public class Example {
public static void printMessage() {
System.out.println("Hello");
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
printMessage();
}
}
}
This code calls a method that prints a message five times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
printMessage()method inside the loop. - How many times: 5 times, once for each loop iteration.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 method calls |
| 10 | 10 method calls |
| 100 | 100 method calls |
Pattern observation: The number of method calls grows directly with the number of loop iterations.
Time Complexity: O(n)
This means the total time grows in a straight line as we increase the number of method calls.
[X] Wrong: "Calling a method inside a loop is always slow and complex like nested loops."
[OK] Correct: Here, the method is called once per loop iteration, so the time grows simply with the number of calls, not more complex.
Understanding how method calls add up helps you explain code efficiency clearly and shows you can think about how programs grow with input.
"What if the method called inside the loop itself contains a loop? How would the time complexity change?"
