0
0
Javaprogramming~15 mins

Public access modifier in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: Public access modifier
O(n)
menu_bookUnderstanding Time 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.

code_blocksScenario Under Consideration

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.

repeatIdentify Repeating Operations

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.
search_insightsHow Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

Pattern observation: The time to sum grows directly with the number of items. More items mean more work.

cards_stackFinal Time Complexity

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.

chat_errorCommon Mistake

[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.

business_centerInterview Connect

Understanding how access modifiers relate to performance shows you know both design and efficiency, a great skill to share in interviews.

psychology_altSelf-Check

"What if the sumArray method used recursion instead of a loop? How would the time complexity change?"