Classes and objects in Java - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?"
Practice
class in Java?Solution
Step 1: Understand the role of a class
A class defines the structure and behavior that objects created from it will have.Step 2: Identify the correct purpose
Classes are not for running programs or storing data on disk; they are blueprints for objects.Final Answer:
To serve as a blueprint for creating objects -> Option AQuick Check:
Class = blueprint for objects [OK]
- Confusing classes with methods
- Thinking classes store data permanently
- Believing classes execute the program
Car in Java?Solution
Step 1: Recall object creation syntax
In Java, objects are created using thenewkeyword followed by the class constructor with parentheses.Step 2: Check each option
Car myCar = new Car(); uses correct syntax:Car myCar = new Car();. Others miss parentheses or have wrong order.Final Answer:
Car myCar = new Car(); -> Option CQuick Check:
Usenew ClassName()to create objects [OK]
- Omitting parentheses after class name
- Placing 'new' keyword incorrectly
- Missing semicolon at the end
class Dog {
String name;
void bark() {
System.out.println(name + " says Woof!");
}
}
public class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.name = "Buddy";
dog1.bark();
}
}Solution
Step 1: Understand object property assignment
The objectdog1has itsnameset to "Buddy" before callingbark().Step 2: Analyze the bark method output
The method prints thenamefollowed by " says Woof!" so it prints "Buddy says Woof!".Final Answer:
Buddy says Woof! -> Option DQuick Check:
Object property used in method = Buddy says Woof! [OK]
- Assuming default null value prints
- Forgetting to assign the name
- Thinking method prints only 'Woof!'
class Person {
String name;
void setName(String name) {
name = name;
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.name);
}
}Solution
Step 1: Analyze the setName method
The assignmentname = name;assigns the parameter to itself, not to the instance variable.Step 2: Understand instance variable shadowing
To assign correctly, usethis.name = name;to refer to the instance variable.Final Answer:
The method setName does not assign the parameter to the instance variable -> Option BQuick Check:
Use 'this' to assign instance variables [OK]
- Confusing parameter and instance variable names
- Forgetting 'this' keyword
- Assuming assignment works without 'this'
Rectangle object with double the width and height of the current one?class Rectangle {
int width;
int height;
Rectangle(int w, int h) {
width = w;
height = h;
}
// Your method here
}Solution
Step 1: Understand the requirement
The method should return a new Rectangle object with width and height doubled, without changing the current object.Step 2: Evaluate each option
Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } creates and returns a new Rectangle with doubled dimensions. void doubleSize() { width *= 2; height *= 2; } changes current object and returns void. Rectangle doubleSize() { width *= 2; height *= 2; return this; } changes current object and returns it. Rectangle doubleSize() { return new Rectangle(width + 2, height + 2); } adds 2 instead of doubling.Final Answer:
Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } -> Option AQuick Check:
Return new object with doubled size = Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } [OK]
- Modifying current object instead of returning new
- Adding instead of multiplying dimensions
- Returning void instead of new object
