AP Computer Science A · Topic 5.5
Mutator Methods Practice
Part of Writing Classes.
Practice questions
8
Sample questions
5 of 8 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
public class Box { private int size; public Box() { size = 1; } public void setSize(int s) { size = s; } public int getSize() { return size; } } // ... Box b = new Box(); b.setSize(10); System.out.println(b.getSize());What is printed?
- A
1
- B
0
- C
Compile-time error
- Dcheck_circle
10
Why
The mutator setSize assigns 10 to size, which getSize then returns.
- A
Sample 2difficulty 2/5
public class Age { private int years; public void setYears(int y) { if (y >= 0) years = y; } public int getYears() { return years; } } // ... Age a = new Age(); a.setYears(-3); a.setYears(20); System.out.println(a.getYears());What is printed?
- A
-3
- Bcheck_circle
20
- C
0
- D
17
Why
The negative value is rejected by the validation guard; setting 20 succeeds.
- A
Sample 3difficulty 2/5
public class Switch { private boolean on; public void toggle() { on = !on; } public boolean isOn() { return on; } } // ... Switch s = new Switch(); s.toggle(); s.toggle(); s.toggle(); System.out.println(s.isOn());What is printed?
- A
Compile-time error
- B
false
- C
1
- Dcheck_circle
true
Why
Starting from false: toggle to true, toggle to false, toggle to true. Final value true.
- A
Sample 4difficulty 3/5
public class Stat { private int total = 0; private int count = 0; public void add(int v) { total += v; count++; } public double avg() { if (count == 0) return 0; return (double) total / count; } } // ... Stat s = new Stat(); s.add(2); s.add(4); s.add(6); System.out.println(s.avg());What is printed?
- A
0.0
- B
3.0
- Ccheck_circle
4.0
- D
12.0
Why
total=12 and count=3; 12.0/3 yields 4.0.
- A
Sample 5difficulty 3/5
A typical "setter" for <code>private int age;</code>
- A
private void setAge(int a) { age = a; }
- Bcheck_circle
public void setAge(int a) { age = a; }
- C
public void setAge() { age = 0; }
- D
public int setAge(int a) { age = a; }
Why
Setters return void and take a parameter for the new value.
- A