AP Computer Science A · Topic 5.4
Accessor Methods Practice
Part of Writing Classes.
Practice questions
5
Sample questions
5 of 5 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 1/5
public class Student { private String name; public Student(String n) { name = n; } public String getName() { return name; } } // ... Student s = new Student("Ana"); System.out.println(s.getName());What is printed?
- A
Compile-time error
- B
null
- C
name
- Dcheck_circle
Ana
Why
The accessor method getName returns the instance variable name, which was set to "Ana" by the constructor.
- A
Sample 2difficulty 2/5
public class Temp { private double celsius; public Temp(double c) { celsius = c; } public double toFahrenheit() { return celsius * 9.0 / 5.0 + 32; } } // ... Temp t = new Temp(100); System.out.println(t.toFahrenheit());What is printed?
- Acheck_circle
212.0
- B
100.0
- C
180.0
- D
32.0
Why
100 * 9/5 + 32 = 180 + 32 = 212.0.
- A
Sample 3difficulty 3/5
public class Wrap { private StringBuilder b = new StringBuilder("hi"); public StringBuilder getB() { return b; } } // ... Wrap w = new Wrap(); w.getB().append("!"); System.out.println(w.getB());What is printed?
- Acheck_circle
hi!
- B
!
- C
hi
- D
Compile-time error
Why
The getter returns the same mutable reference; appending modifies the underlying StringBuilder.
- A
Sample 4difficulty 3/5
A typical "getter" for <code>private int age;</code>
- A
public int age() { age++; }
- B
public void getAge() { return age; }
- C
public static int getAge();
- Dcheck_circle
public int getAge() { return age; }
Why
Returns the field; non-static; no parameters.
- A
Sample 5difficulty 3/5
public class Group { private int[] data; public Group(int[] d) { data = new int[d.length]; for (int i = 0; i < d.length; i++) data[i] = d[i]; } public int[] getData() { int[] copy = new int[data.length]; for (int i = 0; i < data.length; i++) copy[i] = data[i]; return copy; } } // ... int[] a = {1, 2, 3}; Group g = new Group(a); int[] view = g.getData(); view[1] = 100; System.out.println(a[1] + "," + g.getData()[1]);What is printed?
- A
2,100
- B
100,100
- C
100,2
- Dcheck_circle
2,2
Why
Both the constructor and accessor make defensive copies, so neither g's data nor a are affected by changes to view.
- A