Instance methods in Java - Time & Space Complexity
We want to understand how the time it takes to run instance methods changes as the input grows.
How does calling an instance method affect the program's speed when data size changes?
Analyze the time complexity of the following code snippet.
public class Counter {
private int count = 0;
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
This code defines an instance method that increases a number and another that returns it.
Look for loops or repeated actions inside the methods.
- Primary operation: Simple increment or return of a value.
- How many times: Each method runs once per call, no loops inside.
Since the methods do a fixed small task, time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 simple step |
| 100 | 1 simple step |
| 1000 | 1 simple step |
Pattern observation: Time grows directly with how many times you call the method, but each call is very fast and simple.
Time Complexity: O(1)
This means each instance method call takes the same small amount of time, no matter the input size.
[X] Wrong: "Instance methods always take longer if the object has more data."
[OK] Correct: The time depends on what the method does, not just the object size. Simple methods run quickly regardless.
Understanding how instance methods work helps you explain code efficiency clearly and confidently in interviews.
"What if the instance method included a loop over a list inside the object? How would the time complexity change?"