AP Computer Science A · Topic 5.5

Mutator Methods Practice

Part of Writing Classes.

Practice questions

8

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 8 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. 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

    • D

      10

      check_circle

    Why

    The mutator setSize assigns 10 to size, which getSize then returns.

  2. 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

    • B

      20

      check_circle
    • C

      0

    • D

      17

    Why

    The negative value is rejected by the validation guard; setting 20 succeeds.

  3. 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

    • D

      true

      check_circle

    Why

    Starting from false: toggle to true, toggle to false, toggle to true. Final value true.

  4. 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

    • C

      4.0

      check_circle
    • D

      12.0

    Why

    total=12 and count=3; 12.0/3 yields 4.0.

  5. Sample 5difficulty 3/5

    A typical "setter" for <code>private int age;</code>

    • A

      private void setAge(int a) { age = a; }

    • B

      public void setAge(int a) { age = a; }

      check_circle
    • 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.