Public access modifier in Java - Time & Space Complexity
Let's see how using the public access modifier affects the time it takes for a program to run.
We want to know if making something public changes how long the program works as it grows.
Analyze the time complexity of the following code snippet.
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int sumArray(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
}
This class has public methods to add two numbers and to sum all numbers in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-each loop that goes through each number in the array.
- How many times: It runs once for every item in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The time to sum grows directly with the number of items. More items mean more work.
Time Complexity: O(n)
This means the time to run the sumArray method grows in a straight line with the size of the input array.
[X] Wrong: "Making methods public makes the program slower because anyone can access them."
[OK] Correct: The public access modifier only controls who can use the method, not how fast it runs. The speed depends on what the method does, not its access level.
Understanding how access modifiers relate to performance shows you know both design and efficiency, a great skill to share in interviews.
"What if the sumArray method used recursion instead of a loop? How would the time complexity change?"
