0
0
Javaprogramming~5 mins

Object interaction in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Object interaction
O(n)
Understanding Time Complexity

When objects talk to each other in a program, it takes time. We want to see how this time grows when we have more objects or more interactions.

How does the number of object interactions affect the program's speed?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Person {
    void greet(Person other) {
        System.out.println("Hello, " + other.getName());
    }
    String getName() {
        return "Friend";
    }
}

class Demo {
    static void greetAll(Person[] people) {
        for (Person p : people) {
            p.greet(p);
        }
    }
}
    

This code makes each person greet themselves by calling a method on each object in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array of Person objects and calling greet on each.
  • How many times: Once for each person in the array (n times).
How Execution Grows With Input

As the number of people grows, the number of greetings grows the same way.

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

Pattern observation: The work grows directly with the number of people.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of people, the time to greet doubles too.

Common Mistake

[X] Wrong: "Calling a method on an object inside a loop makes the time complexity more than linear."

[OK] Correct: Each method call here is simple and happens once per object, so it adds a fixed amount of work per item, keeping the growth linear.

Interview Connect

Understanding how objects interact and how that affects time helps you explain your code clearly and think about efficiency in real projects.

Self-Check

"What if greet called another method that loops over all people? How would the time complexity change?"