0
0
Javaprogramming~5 mins

Default constructor in Java - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default constructor
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we increase n, we create more Box objects, so the work grows directly with n.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: Doubling n doubles the number of objects created and the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of objects created.

Common Mistake

[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.

Interview Connect

Understanding how object creation scales helps you reason about program speed and resource use in real projects.

Self-Check

What if the constructor did some work like initializing a large array? How would the time complexity change?