Why methods are needed in Java - Deep Dive with Evidence
We want to see how using methods affects the time it takes for a program to run.
How does breaking code into methods change the work done as input grows?
Analyze the time complexity of the following code snippet.
public class Calculator {
public int addNumbers(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
public void printSum(int[] numbers) {
int total = addNumbers(numbers);
System.out.println("Sum: " + total);
}
}
This code adds numbers in an array using a method, then prints the result using another method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop through the array to add numbers.
- How many times: Once for each number in the array.
As the array gets bigger, the loop runs more times to add all numbers.
| 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.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line as the list gets longer.
[X] Wrong: "Using methods makes the program slower because of extra calls."
[OK] Correct: Methods organize code but do not add extra loops or slow down the main work. The main time depends on the loop inside the method.
Understanding how methods affect time helps you write clear code without worrying about hidden slowdowns. It shows you can organize work while keeping performance steady.
"What if the addNumbers method called itself recursively instead of using a loop? How would the time complexity change?"
