0
0
Javaprogramming~15 mins

Static methods in Java - Time & Space Complexity

Choose your learning style8 modes available
scheduleTime Complexity: Static methods
O(n)
menu_bookUnderstanding Time Complexity

Let's see how the time it takes to run static methods changes as we use them more.

We want to know how the work done grows when calling static methods in a program.

code_blocksScenario Under Consideration

Analyze the time complexity of the following code snippet.


public class Calculator {
    public static int square(int n) {
        return n * n;
    }

    public static void printSquares(int[] numbers) {
        for (int num : numbers) {
            System.out.println(square(num));
        }
    }
}
    

This code defines a static method to square a number and another static method to print squares of all numbers in an array.

repeatIdentify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array in printSquares and calling square for each element.
  • How many times: Once for each element in the input array.
search_insightsHow Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
1010 calls to square and 10 print operations
100100 calls to square and 100 print operations
10001000 calls to square and 1000 print operations

Pattern observation: The work grows directly with the number of elements; doubling the input doubles the work.

cards_stackFinal Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items you process.

chat_errorCommon Mistake

[X] Wrong: "Static methods always run faster and take constant time no matter what."

[OK] Correct: Static means the method belongs to the class, not an object, but the time depends on what the method does and how many times it runs.

business_centerInterview Connect

Understanding how static methods behave helps you explain code efficiency clearly and confidently in real projects and interviews.

psychology_altSelf-Check

"What if the square method called itself recursively? How would the time complexity change?"