Getter and setter methods in Java - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to see how the time it takes to run getter and setter methods changes as the program runs.
How does the work grow when we use these methods more?
Analyze the time complexity of the following code snippet.
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String newName) {
this.name = newName;
}
}
This code defines simple getter and setter methods to read and update a person's name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing or updating a single variable.
- How many times: Each method runs once per call, no loops or repeated steps inside.
Each getter or setter does a fixed amount of work regardless of input size.
| Number of Method Calls (n) | Approx. Operations |
|---|---|
| 10 | 10 simple operations |
| 100 | 100 simple operations |
| 1000 | 1000 simple operations |
Pattern observation: The work grows directly with how many times you call the methods, but each call is very quick and simple.
Time Complexity: O(1)
This means each getter or setter runs in constant time, no matter how big your program or data is.
[X] Wrong: "Getter and setter methods take longer as the program gets bigger."
[OK] Correct: Each getter or setter just reads or writes one value, so the time does not depend on program size.
Understanding that simple methods like getters and setters run quickly helps you explain how your code handles data efficiently.
"What if a getter method computed a value by looping through a list? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of getters and setters
Getters and setters are methods used to access and modify private variables safely.Step 2: Identify their purpose in encapsulation
They help protect data by controlling how variables are read or changed from outside the class.Final Answer:
To control access to private variables by reading and updating their values -> Option BQuick Check:
Getters and setters control access [OK]
- Thinking getters and setters create objects
- Confusing getters/setters with printing methods
- Assuming they perform calculations
age?Solution
Step 1: Identify setter method structure
A setter method is public, returns void, and takes a parameter to update the private variable.Step 2: Check the parameter assignment
The method assigns the parameter value to the instance variable usingthis.age = age;.Final Answer:
public void setAge(int age) { this.age = age; } -> Option CQuick Check:
Setter syntax = public void setVar(Type var) { this.var = var; } [OK]
- Using return type int for setter
- Assigning instance variable to parameter instead of reverse
- Making setter private
public class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.getName());
}
}Solution
Step 1: Trace the setter method call
ThesetNamemethod sets the private variablenameto "Alice".Step 2: Trace the getter method call
ThegetNamemethod returns the value ofname, which is now "Alice".Final Answer:
Alice -> Option AQuick Check:
Setter sets "Alice", getter returns "Alice" [OK]
- Expecting null because variable is private
- Thinking code causes compilation error
- Assuming output is empty line
public void setScore(int score) {
score = score;
}Solution
Step 1: Understand variable shadowing
The parameterscoreshadows the instance variablescore, soscore = score;assigns parameter to itself.Step 2: Fix assignment using
Usethisthis.score = score;to assign the parameter value to the instance variable.Final Answer:
Usethis.score = score;to assign parameter to instance variable -> Option DQuick Check:
Use this.variable = parameter to fix shadowing [OK]
- Assigning parameter to itself
- Changing return type incorrectly
- Making setter private unnecessarily
temperature. You want to ensure the temperature can only be set between 0 and 100. Which setter method correctly enforces this rule?Solution
Step 1: Understand the requirement
The setter must only allow values between 0 and 100 inclusive.Step 2: Analyze each option
public void setTemperature(int temperature) { if (temperature >= 0 && temperature <= 100) this.temperature = temperature; } sets temperature only if in range but does nothing if out of range (temperature remains unchanged). public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } sets temperature to 0 if out of range, enforcing a default safe value.Step 3: Choose the best enforcement
public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } actively prevents invalid values by resetting to 0, ensuring temperature is always valid.Final Answer:
public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } -> Option AQuick Check:
Setter enforces range with else and default value [OK]
- Ignoring invalid values without handling
- Returning int from setter
- Not using else to handle out-of-range values
