Method overloading in Java - Time & Space Complexity
We want to understand how the time it takes to run a program changes when using method overloading.
Specifically, does having multiple methods with the same name but different inputs affect how long the program runs?
Analyze the time complexity of the following code snippet.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
This code defines two methods named add but with different numbers of inputs. It shows method overloading.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple addition operations inside each method.
- How many times: Each method runs once per call; no loops or recursion.
Since each method just adds a fixed number of numbers, the work does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 or 3 additions (max) |
| 100 | 2 or 3 additions (max) |
| 1000 | 2 or 3 additions (max) |
Pattern observation: The number of operations stays the same no matter how big the input numbers are.
Time Complexity: O(1)
This means the time to run these methods stays constant regardless of input size.
[X] Wrong: "Having multiple methods with the same name makes the program slower because it has to check all of them."
[OK] Correct: The program chooses the right method to run before it starts, so it does not waste time checking at runtime.
Understanding method overloading helps you write clear code and shows you know how programs pick the right method quickly.
"What if one of the overloaded methods used a loop to add numbers? How would the time complexity change?"
