Bird
Raised Fist0
Javaprogramming~20 mins

Getter and setter methods in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Getter and Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of getter and setter usage
What is the output of this Java program that uses getter and setter methods?
Java
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());
    }
}
AAlice
Bnull
CCompilation error
DRuntime error
Attempts:
2 left
πŸ’‘ Hint
Look at what value is assigned using the setter before printing with the getter.
❓ Predict Output
intermediate
2:00remaining
Value of private field after setter call
What is the value of the private field 'age' after running this code?
Java
public class Animal {
    private int age;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        }
    }
    public static void main(String[] args) {
        Animal a = new Animal();
        a.setAge(-5);
        System.out.println(a.getAge());
    }
}
ACompilation error
B0
CRuntime error
D-5
Attempts:
2 left
πŸ’‘ Hint
Check the condition inside the setter before assigning the value.
πŸ”§ Debug
advanced
2:00remaining
Identify the error in setter method
What error will this code cause when compiled or run?
Java
public class Car {
    private String model;
    public void setModel(String model) {
        model = model;
    }
    public String getModel() {
        return model;
    }
    public static void main(String[] args) {
        Car c = new Car();
        c.setModel("Tesla");
        System.out.println(c.getModel());
    }
}
ACompilation error due to variable shadowing
BOutput is Tesla
COutput is null
DRuntime NullPointerException
Attempts:
2 left
πŸ’‘ Hint
Check if the setter actually changes the private field or just the parameter.
πŸ“ Syntax
advanced
2:00remaining
Syntax error in getter method
Which option shows the correct syntax for a getter method for a private int field 'score'?
Apublic int getScore() { return score; }
Bpublic int getScore() return score; }
Cpublic int getScore() { score; }
Dpublic int getScore() { return; }
Attempts:
2 left
πŸ’‘ Hint
A getter must return the field value inside braces with a return statement.
πŸš€ Application
expert
2:00remaining
Effect of setter on immutable field
Given this class, what happens when trying to set the 'id' field using the setter?
Java
public class User {
    private final int id;
    public User(int id) {
        this.id = id;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
}
ASetter is ignored silently
BSetter changes the id successfully
CRuntime error when calling setId
DCompilation error because 'id' is final and cannot be assigned in setter
Attempts:
2 left
πŸ’‘ Hint
Final fields cannot be reassigned after initialization.

Practice

(1/5)
1. What is the main purpose of getter and setter methods in Java?
easy
A. To create new objects from a class
B. To control access to private variables by reading and updating their values
C. To perform arithmetic operations on variables
D. To print values directly to the console

Solution

  1. Step 1: Understand the role of getters and setters

    Getters and setters are methods used to access and modify private variables safely.
  2. Step 2: Identify their purpose in encapsulation

    They help protect data by controlling how variables are read or changed from outside the class.
  3. Final Answer:

    To control access to private variables by reading and updating their values -> Option B
  4. Quick Check:

    Getters and setters control access [OK]
Hint: Getters read, setters update private variables safely [OK]
Common Mistakes:
  • Thinking getters and setters create objects
  • Confusing getters/setters with printing methods
  • Assuming they perform calculations
2. Which of the following is the correct syntax for a setter method for a private int variable named age?
easy
A. private void setAge(int age) { age = this.age; }
B. public int setAge() { return age; }
C. public void setAge(int age) { this.age = age; }
D. public int getAge(int age) { this.age = age; }

Solution

  1. Step 1: Identify setter method structure

    A setter method is public, returns void, and takes a parameter to update the private variable.
  2. Step 2: Check the parameter assignment

    The method assigns the parameter value to the instance variable using this.age = age;.
  3. Final Answer:

    public void setAge(int age) { this.age = age; } -> Option C
  4. Quick Check:

    Setter syntax = public void setVar(Type var) { this.var = var; } [OK]
Hint: Setter methods are void and assign parameter to this.variable [OK]
Common Mistakes:
  • Using return type int for setter
  • Assigning instance variable to parameter instead of reverse
  • Making setter private
3. What will be the output of the following code?
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());
  }
}
medium
A. Alice
B. null
C. Compilation error
D. Empty line

Solution

  1. Step 1: Trace the setter method call

    The setName method sets the private variable name to "Alice".
  2. Step 2: Trace the getter method call

    The getName method returns the value of name, which is now "Alice".
  3. Final Answer:

    Alice -> Option A
  4. Quick Check:

    Setter sets "Alice", getter returns "Alice" [OK]
Hint: Setter sets value, getter returns it [OK]
Common Mistakes:
  • Expecting null because variable is private
  • Thinking code causes compilation error
  • Assuming output is empty line
4. Identify the error in this setter method and choose the correct fix:
public void setScore(int score) {
  score = score;
}
medium
A. Remove parameter from method
B. Change method return type to int
C. Make method private
D. Use this.score = score; to assign parameter to instance variable

Solution

  1. Step 1: Understand variable shadowing

    The parameter score shadows the instance variable score, so score = score; assigns parameter to itself.
  2. Step 2: Fix assignment using this

    Use this.score = score; to assign the parameter value to the instance variable.
  3. Final Answer:

    Use this.score = score; to assign parameter to instance variable -> Option D
  4. Quick Check:

    Use this.variable = parameter to fix shadowing [OK]
Hint: Use this.variable to avoid shadowing in setters [OK]
Common Mistakes:
  • Assigning parameter to itself
  • Changing return type incorrectly
  • Making setter private unnecessarily
5. You have a class with a private int field temperature. You want to ensure the temperature can only be set between 0 and 100. Which setter method correctly enforces this rule?
hard
A. public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; }
B. public void setTemperature(int temperature) { this.temperature = temperature; }
C. public int setTemperature(int temperature) { if (temperature > 0) this.temperature = temperature; return temperature; }
D. public void setTemperature(int temperature) { if (temperature >= 0 && temperature <= 100) this.temperature = temperature; }

Solution

  1. Step 1: Understand the requirement

    The setter must only allow values between 0 and 100 inclusive.
  2. 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.
  3. 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.
  4. Final Answer:

    public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } -> Option A
  5. Quick Check:

    Setter enforces range with else and default value [OK]
Hint: Use if-else to enforce valid range in setter [OK]
Common Mistakes:
  • Ignoring invalid values without handling
  • Returning int from setter
  • Not using else to handle out-of-range values