Getters and Setters in AP CSA: Complete Guide (2025-2026)

Getters and Setters in AP CSA: Complete Guide (2025-2026)

Getters (accessors) and setters (mutators) are the controlled interface between private fields and the outside world. They are central to Unit 3 encapsulation and appear on virtually every AP CSA exam in both MCQ and FRQ sections. This guide covers how to write them correctly, the traps students fall into, and the exam strategies that earn full points.

What Are Getters and Setters?

In AP CSA, all instance variables should be private. Getters and setters give controlled public access:

  • Getter (accessor): returns the value of a field. Must not modify state.
  • Setter (mutator): changes the value of a field. Can validate before assigning.

Getters and setters are Unit 3 (Class Creation) content and account for 10–18% of the exam score. FRQ parts that say “write accessor methods” or “write a mutator” are testing exactly this skill.

Naming Conventions

  • Getter: get + FieldName → getName(), getScore()
  • Boolean getter: is + FieldName → isActive(), isValid()
  • Setter: set + FieldName → setName(String n)
  • Return type of getter matches the field's type exactly
  • Setter return type is always void

Code Examples

Example 1: Standard Getter and Setter Pair

What does the final println print?
public class Thermostat {
    private double temp;

    public double getTemp() {
        return temp;
    }

    public void setTemp(double t) {
        if (t >= -40 && t <= 120) {
            temp = t;
        }
    }

    public static void main(String[] args) {
        Thermostat th = new Thermostat();
        th.setTemp(72.5);
        th.setTemp(200);   // rejected
        System.out.println(th.getTemp());
    }
}

Example 2: Boolean Field with isXxx Getter

What is printed after toggling active twice?
public class Device {
    private boolean active;

    public boolean isActive() { return active; }
    public void setActive(boolean a) { active = a; }

    public static void main(String[] args) {
        Device d = new Device();
        System.out.println(d.isActive()); // default
        d.setActive(true);
        d.setActive(!d.isActive());
        System.out.println(d.isActive());
    }
}

Example 3: Chained Setters and Computed Getter

What does the formatted getter return?
public class Product {
    private String name;
    private double price;

    public String getName() { return name; }
    public double getPrice() { return price; }
    public void setName(String n) { name = n; }
    public void setPrice(double p) { if (p >= 0) price = p; }
    public String getLabel() { return name + ": $" + price; }

    public static void main(String[] args) {
        Product prod = new Product();
        prod.setName("Widget");
        prod.setPrice(4.99);
        prod.setPrice(-1);  // rejected
        System.out.println(prod.getLabel());
    }
}

Common Pitfalls

1. Getter That Modifies State

A getter that increments, randomizes, or otherwise changes a field is a side-effect bug. The exam specifically tests this and it destroys encapsulation.

2. Local Variable Shadowing the Field

Writing String name = "default"; return name; inside a getter ignores the field entirely. Return this.name or simply return name without the local declaration.

3. Wrong Return Type on Getter

If the field is double, the getter must return double, not int. A narrowing return type causes a compile error (or silent truncation if cast).

4. Setter Returning a Value

Setters must be void. If a setter tries to return the field value, that's a design error—use a separate getter instead.

AP Exam Tip: FRQ rubrics award the getter point for: correct return type, correct field name, no modification of state. Setter points require: correct parameter type, correct assignment. Validation logic earns bonus credit when specified.
⚠ Watch Out: A getter named getActive() for a boolean field is technically valid but non-standard. The conventional Java name is isActive(). AP FRQ specs usually tell you exactly what to name the method—match it precisely.

Check for Understanding

Score: 0 / 0 answered (8 total)
1. A student writes this getter. WHICH problem does it have?
public int getScore() {{
score = score + 1;
return score;
}}
2. Consider these three setter implementations for private int altitude. WHICH correctly enforce that altitude must be between 0 and 40000?

I. public void setAlt(int a) {{ altitude = a; }}
II. public void setAlt(int a) {{ if (a >= 0 && a <= 40000) altitude = a; }}
III. public void setAlt(int a) {{ altitude = Math.max(0, Math.min(40000, a)); }}
3. What does the following code print? PREDICT the output before reading the choices.
public class Lamp {{
private boolean on;
public boolean isOn() {{ return on; }}
public void setOn(boolean state) {{ on = state; }}
}}
Lamp lamp = new Lamp();
lamp.setOn(true);
lamp.setOn(false);
System.out.println(lamp.isOn());
4. A student writes this getter for private String label. WHICH is the correct diagnosis?
public String getLabel() {{
String label = "default";
return label;
}}
5. WHICH of the following statements about getters and setters is ALWAYS true in AP CSA?
6. Given private int capacity = 10, what is the output? PREDICT before choosing.
public void setCapacity(int c) {{
if (c > 0) capacity = c;
}}
setCapacity(-5);
setCapacity(20);
setCapacity(0);
System.out.println(capacity);
7. WHICH accessor method header is correctly written for a field private double voltage?
8. A BankAccount class has private double balance. The setter is:
public void setBalance(double amount) {{
balance = Math.abs(amount);
}}
After calling setBalance(-250.0), what is getBalance()? PREDICT before reading.

Frequently Asked Questions

No. Some fields should be read-only (getter only), especially if changing them would corrupt object state. For example, an ID assigned at construction should have a getter but no setter.

Yes. A method like getFullName() that returns firstName + ' ' + lastName is a perfectly valid accessor. It follows the getter naming convention and does not modify state.

An accessor reads data (returns a value, void-free). A mutator writes data (takes a parameter, returns void). Accessor = getter, mutator = setter.

Technically yes, but the standard AP CSA pattern is one parameter per setter. If you need to update multiple fields, write separate setters or add an update method.

Public fields allow any code to set any value, bypassing validation. Setters let you enforce rules (e.g., reject negative scores). Getters let you return computed or formatted versions of data. This is the core of encapsulation.

1-on-1 Expert Support

Need help writing correct getter/setter methods for the FRQ? An AP CSA teacher with a 54% five-rate is available for personalized sessions.

View Tutoring Options

Related Topics

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

tanner@apcsexamprep.com

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at tanner@apcsexamprep.com