0
0
Javaprogramming~5 mins

Parameterized constructor in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Parameterized constructor
O(n)
Understanding Time Complexity

Let's see how the time it takes to run a parameterized constructor changes as we create more objects.

We want to know how the work grows when we make many objects using this constructor.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Creating multiple Person objects
for (int i = 0; i < n; i++) {
    Person p = new Person("Name" + i, i);
}

This code defines a parameterized constructor and creates n Person objects using it.

Identify Repeating Operations
  • Primary operation: Creating a Person object using the constructor.
  • How many times: The constructor runs once for each of the n objects in the loop.
How Execution Grows With Input

Each new object requires the constructor to run once, so the total work grows directly with the number of objects.

Input Size (n)Approx. Operations
1010 constructor calls
100100 constructor calls
10001000 constructor calls

Pattern observation: The work increases evenly as we create more objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to create n objects grows in a straight line with n.

Common Mistake

[X] Wrong: "The constructor runs only once no matter how many objects we create."

[OK] Correct: Each object needs its own constructor call, so the constructor runs n times for n objects.

Interview Connect

Understanding how constructors work with many objects helps you explain how your code scales in real projects.

Self-Check

"What if the constructor did some extra work inside a loop? How would that affect the time complexity?"