Challenge - 5 Problems
Getter and Setter Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2: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()); } }
Attempts:
2 left
π‘ Hint
Look at what value is assigned using the setter before printing with the getter.
β Incorrect
The setter method sets the private field 'name' to "Alice". The getter returns this value, so the output is "Alice".
β Predict Output
intermediate2: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()); } }
Attempts:
2 left
π‘ Hint
Check the condition inside the setter before assigning the value.
β Incorrect
The setter only assigns age if the value is greater than 0. Since -5 is not, age remains at default 0.
π§ Debug
advanced2: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()); } }
Attempts:
2 left
π‘ Hint
Check if the setter actually changes the private field or just the parameter.
β Incorrect
The setter assigns the parameter to itself, not to the field. So the field remains null and output is null.
π Syntax
advanced2:00remaining
Syntax error in getter method
Which option shows the correct syntax for a getter method for a private int field 'score'?
Attempts:
2 left
π‘ Hint
A getter must return the field value inside braces with a return statement.
β Incorrect
Option A correctly defines a method returning the field value. Others have syntax errors or missing return.
π Application
expert2: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; } }
Attempts:
2 left
π‘ Hint
Final fields cannot be reassigned after initialization.
β Incorrect
The setter tries to assign a final field which causes a compilation error.