Practice Dojo

AP Computer Science A › Unit 3

AP Computer Science A Unit 3: Class Creation

10 to 18% of the exam · 180 practice questions · 5 free-response questions

Unit 3 moves from using classes to writing them. You will design a class with private instance variables, constructors, and methods, and learn about static members, scope, access, and the this keyword. The free-response section includes a class design question, where you write a complete class from a description and examples. A common error is redeclaring an instance variable as a local variable inside a constructor, so the field never gets set. Students also confuse static and instance members, or try to return a value from a void method.

Practice this unit

White belt · 60 questionsRegular · 60 questionsBlack belt · 60 questionsFree response

White belt covers core terms and foundational ideas, Regular is set at exam level, and Black belt has harder multi-step questions.

Topics in this unit

Free-response questions

Sample questions

These are taken from the Regular set, with the answer and explanation shown.

Topic 3.3 Anatomy of a Class

1. A class Employee has a private instance variable salary and public methods getSalary and raise. Which of the following best describes the benefit of this design?

  1. AThe variable salary is shared by all Employee objects
  2. BThe class controls how the value of salary can be read and changed
  3. COther classes can read and change salary directly
  4. DThe methods run faster than direct access

Answer: B. Keeping the variable private is data encapsulation. Code outside of the class must go through the public methods, so the class decides what is allowed, for example whether a raise can be negative.

Common trap: Choosing "other classes can read and change salary directly". Private variables are exactly the ones other classes cannot use directly.

Topic 3.5 Methods: How to Write Them

2. Consider the following class.

  1. A16
  2. B9
  3. C15
  4. D14

Answer: C. twice(addOne(3)) is twice(4), which is 8. addOne(twice(3)) is addOne(6), which is 7. The sum is 15.

Common trap: Choosing 16. That treats both halves as twice(addOne(3)). The order of the calls matters.

Topic 3.8 Scope and Access

3. Consider the following code segment.

  1. A3
  2. BThe code does not compile because i is declared twice
  3. C11
  4. D14

Answer: D. Each for loop declares its own loop variable, whose scope is only that loop, so the same name can be used again in the next loop. The first loop adds 0 + 1 + 2 = 3, and the second adds 5 + 6 = 11, for a total of 14.

Common trap: Choosing "does not compile because i is declared twice". The two declarations have separate scopes, so there is no conflict.

Start practicing Unit 3 →