Parameterized constructor in Java - Time & Space 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.
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.
- 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.
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 |
|---|---|
| 10 | 10 constructor calls |
| 100 | 100 constructor calls |
| 1000 | 1000 constructor calls |
Pattern observation: The work increases evenly as we create more objects.
Time Complexity: O(n)
This means the time to create n objects grows in a straight line with n.
[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.
Understanding how constructors work with many objects helps you explain how your code scales in real projects.
"What if the constructor did some extra work inside a loop? How would that affect the time complexity?"