Unit 3 Cycle 1 Day 5: Mutator Methods

Unit 3 Foundation (Cycle 1) Day 5 of 28 Foundation

Mutator Methods

Section 3.5 — Mutator Methods

Key Concept

Mutator methods (setters) modify the value of one or more private instance variables. They are typically void methods named setFieldName(newValue). Mutators enable controlled modification by validating input before changing state. For example, setAge(int age) might check that the value is positive before assigning it. On the AP exam, mutators may modify multiple fields or have side effects like incrementing a counter. The key distinction from accessors is that mutators change the object's state.

Consider the following class.

public class Counter { private int count; public Counter() { count = 0; } public void increment() { count++; } public void reset() { count = 0; } public int getCount() { return count; } }

What is printed after executing the following code?
Counter c = new Counter(); c.increment(); c.increment(); c.increment(); c.reset(); c.increment(); System.out.println(c.getCount());

Answer: (B) 1

count starts at 0. Three increments: count=3. reset(): count=0. One increment: count=1. getCount() returns 1.

Why Not the Others?

(A) reset() sets count back to 0, so the three prior increments are lost.

(C) 3 is the count before reset, but reset clears it to 0.

(D) After reset, there is one more increment, so count is 1, not 0.

Common Mistake

Mutator methods modify instance variables. reset() sets count back to 0, erasing previous increments. Only the increment after reset counts.

AP Exam Tip

Trace method calls in order. Each mutator changes the object's state. Watch for reset-type methods that undo previous changes.

Review this topic: Section 3.5 — Mutator Methods • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.