Default constructor in Java - Time & Space Complexity
Let's see how the time it takes to run code with a default constructor changes as we create more objects.
We want to know how the work grows when making many objects using the default constructor.
Analyze the time complexity of the following code snippet.
public class Box {
public Box() {
// Default constructor does nothing special
}
}
public class Main {
public static void main(String[] args) {
int n = 1000;
for (int i = 0; i < n; i++) {
Box b = new Box();
}
}
}
This code creates n Box objects using the default constructor inside a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new Box object by calling the default constructor.
- How many times: Exactly n times, once for each loop iteration.
Each time we increase n, we create more Box objects, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: Doubling n doubles the number of objects created and the work done.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects created.
[X] Wrong: "Creating objects with a default constructor takes constant time no matter how many objects we make."
[OK] Correct: Each object creation takes some time, so making more objects means more total time, growing with n.
Understanding how object creation scales helps you reason about program speed and resource use in real projects.
What if the constructor did some work like initializing a large array? How would the time complexity change?