Classes and objects in Java - Time & Space Complexity
We want to understand how the time to run code with classes and objects changes as we create more objects or call methods.
How does the program's work grow when we use more objects?
Analyze the time complexity of the following code snippet.
public class Box {
int length, width, height;
public Box(int l, int w, int h) {
length = l;
width = w;
height = h;
}
public int volume() {
return length * width * height;
}
}
public class Main {
public static void main(String[] args) {
Box[] boxes = new Box[100];
for (int i = 0; i < boxes.length; i++) {
boxes[i] = new Box(i, i+1, i+2);
System.out.println(boxes[i].volume());
}
}
}
This code creates 100 Box objects, each with different sizes, and prints their volumes.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that creates and processes each Box object.
- How many times: It runs once for each box, so 100 times in this example.
As the number of boxes increases, the program does more work creating and calculating volumes for each box.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 creations and volume calculations |
| 100 | About 100 creations and volume calculations |
| 1000 | About 1000 creations and volume calculations |
Pattern observation: The work grows directly with the number of boxes; doubling boxes doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of objects created and processed.
[X] Wrong: "Creating objects inside a loop is instant and does not affect time much."
[OK] Correct: Each object creation and method call takes time, so more objects mean more total work.
Understanding how object creation and method calls scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we added a nested loop inside the volume method that runs n times? How would the time complexity change?"