0
0
Javaprogramming~15 mins

Method declaration in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: Method declaration
O(n)
menu_bookUnderstanding Time Complexity

When we look at a method declaration, we want to understand how the time it takes to run changes as the input changes.

We ask: How does the work inside the method grow when inputs get bigger?

code_blocksScenario Under Consideration

Analyze the time complexity of the following code snippet.


public int sumArray(int[] numbers) {
    int sum = 0;
    for (int num : numbers) {
        sum += num;
    }
    return sum;
}
    

This method adds all numbers in an array and returns the total sum.

repeatIdentify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-each loop that adds each number to sum.
  • How many times: Once for each element in the input array.
search_insightsHow Execution Grows With Input

As the array gets bigger, the method does more additions, one for each number.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of items in the array.

cards_stackFinal Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

chat_errorCommon Mistake

[X] Wrong: "The method takes the same time no matter how big the array is."

[OK] Correct: Because the method must add each number, more numbers mean more work and more time.

business_centerInterview Connect

Understanding how loops inside methods affect time helps you explain your code clearly and shows you know how programs grow with input.

psychology_altSelf-Check

"What if we changed the method to sum only the first half of the array? How would the time complexity change?"