The 2009 AP® Computer Science A
Released Exam
 
Contains:
= Multiple-Choice Questions, Answer Key, and Diagnostic Guide
= Free-Response Questions with:
+ Scoring Guidelines
+ Sample Student Responses
+ Scoring Commentary
= Statistical Information About Student Performance on the 2009 Exam
 
  
Materials included in this Released Bxam may not reflect the current AP Course Description and exam in
this subject, and teachers are advised to take this into account as they tise these materials to support theit
 
ation about this AP course and exam, please download the
official AP Course Description from the AP Central* Web site at apcentral.collegeboard.com.
anstructi
 
ef students. For up-to-date infonshapter I: The AP’ Process
Nhat Is the Purpose of the AP® Computer Science A
‘am?
Who Develops the Exam?
Jow Is the Exam Developed?
Section I—Multiple Choice
Section II—Free Response
Question Types
Multiple Choice
Free Response
icoring the Exam
‘Who Scores the AP Computer Science A Exam?
Ensuring Accuracy
How the Scoring Guidelines Are Created
Training Readers to Apply the Scoring Guidelines
Maintaining the Scoring Guidelines
Preparing Students for the Exam
Essential Features of Student Responses
‘Teaching Free-Response Writing
+ chapter will give you a brief overview of the
slopment and scoring processes for the AP Computer
nee A Exam. You can find more detailed information
P Central® (apcentralcollegeboard.com)
 
aat Is the Purpose of the
’ Computer Science A Exam?
AP Computer Science A Exam is designed to allow
lents to demonstrate that their knowledge, under-
ding, and skills are equivalent to those gained by
lents who have successfully completed an introductory
2ge-level course in computer science. The AP Computer
nce A Exam includes material that is covered in a
-semester computer science course in which the Java
gramming language is used to illustrate an object-
ited approach to problem solving and algorithm
slopment. :
he multiple-choice section of the exam is designed to
zr the breadth of the curriculum in terms of knowledge,
«ciples, and conceptual understanding. The free
vonse section requires students to solve problems
vlving more extended reasoning. In both sections,
lents must demonstrate their ability to design, write,
yyze, and document programs and subprogeams
Lifying scores on the AP Computer Science A Exam
* allow students to begin their college careers with credit
an introductory computer science course and/or
ribution credit for a computer science course
Who Develops the Exam?
‘The AP Computer Science Development Committee,
working with Assessment Specialists at ETS, develops the
exam. This committee is appointed by the College Board
and is composed of six teachers from secondary schools,
colleges, and universities in the United States. The members
provide different perspectives: high school teachers offer
valuable advice regarding realistic expectations when
‘matters of content coverage, skills required, and clarity of
phrasing are addressed. College and university faculty
_members ensure that the questions are at the appropriate
level of difficulty for students planning to continue their
studies at colleges and universities. Committee members
typically serve one to four years.
‘Also aiding in the exam development process is the Chief
Reader, the college computer science professor responsible
for supervising the scoring of the free-response questions at
the AP Reading. The Chief Reader attends every committee
‘meeting to ensure that the free-response questions selected
for the exam can be scored reliably. The expertise of the Chief
Reader and the committee members who have scored exams
in past years is notable: they bring to bear their valuable
‘experience from past AP Readings and suggest changes to
improve the quality and the performance of the questions. In
addition, ETS computer science Assessment Specialists offer
their guidance and advice.
 
How Is the Exam Developed?
‘The Development Committee sets the exam specifications,
determining what will be tested and how it will be tested.
also determines the appropriate level of dificulty for the
exam, based on its understanding of the level of competence
required for success in introductory computer science
courses in colleges and universities. Each AP Computer
Science A Exam is the result of several stages of
development that together span two or more years.
Section I—Multiple Choice
  
1. Development Committee members and other faculty
‘write and submit multiple-choice questions directed to
the major topics outlined in the AP Computer Science A
Course Description
2. ETS Assessment Specialists perform preliminary reviews
to ensure that the multiple-choice questions are worded
clearly and concisely3. At the committee meetings, which are held two or three
timesa year, the committee members review, revise, and
approve the draft questions for use on future exams, They
ensure that the questions are clear and unambiguous, that
each question has only one correct answer, and that the
difficulty level ofthe questions is appropriate.
4, Most of the approved draft questions are pretested in
college classes to obtain some estimate ofthe questions
level of difficulty.
5. From the pool of approved questions, ETS Assessment
Specialists select an appropriate mix of materials for the
‘multiple-choice section of an exam, making sure that
the questions are distributed across the content areas
as specified by the Development Committee in the
AP Computer Science A Course Description.
6. The committee thoroughly reviews the draft exam in
various stages of its development, revising the individual
{questions and the mix of questions until itis satisfied with
the result
“The committee contls the difficulty le
 
el ofthe multiple-
choice section by selecting a wide range of questions, a sub-
set of which has been used in an earlier form of the exam.
Section IJ—Free Response
1. Wellin advance ofthe exam administration, the members
of the Development Committee write free-response
{questions for the exam, These are assembled into 9
free-response question pool
2. From this pool, the committee selects an appropriate
‘combination of questions tor a particular exam. It reviews
and revises these questions at all stages of development of
that exam to ensure that they are ofthe highest possible
‘quality. The committee considers, for example, whether the
questions will offer an appropriate level of difficulty and
whether they will elicit answers that will allow Readers, the
high school and college computer science teachers who
score the free-response questions, to discriminate among
the responses along the scoring guidelines used for the
different questions. An ideal question enables the stronger
students to demonstrate their accomplishments while
revealing the limitations of less proficient students.
Question Types
“The 2009 AP Computer Science A Exam contains a 75-
minute multiple-choice section consisting of 40 questions
and a 105-minute free-response section consisting of
4 questions. The two sections are designed to complement
each other and to measure a wide range of skills.
Multiple-choice questions are useful for measuring 2
student’ level of competence in a variety of contexts. In
addition, they have three other strengths:
1. They are highly reliable, Reliability, or the likelihood the
students of similar ability levels taking a different form ¢
the exam will receive the same scores, is controlled mon.
effectively with multiple-choice questions than with
free-response questions.
2. ‘They allow the Development Committee to include a
selection of questions at various levels of difficulty, there
ensuring that the measurement of differences in student
achievement is optimized. For AP Exams, the most
important distinctions are between students earning
scores of 2 and 3 and those earning scores of 3 and 4.
‘These distinctions are usually best accomplished by usit
‘many questions of middle difficulty.
3. They allow comparison of the ability level ofthe current
students with those from another year. A number of
questions from an earlier exam ave included in the curre
cone, allowing comparisons to be made between the scor
of the earlier group of students and those of the current
group. This information, along with other data, is used t
establish AP scores that reflect the competence demand
by the Advanced Placement Program® and that can be
legitimately compared with scores from earlier years.
Free-response questions on the AP Computer Science A.
Exam require students to use thei analytical and
organizational skills to reason about and write program,
fragments that fit the specifications given. They allow
students to demonstrate their understanding of program
structure and their ability to translate that understanding
into a concrete solution. The free-response format allows
for the presentation of uncommon yet correct responses
and permits students to demonstrate their mastery of
‘computer science by 2 show of creativity.
‘The free-response and multiple-choice sections are
designed to complement each other and to meet the overal
course objectives and exam specifications. After each exam
administration, the questions in each section are analyzed
both individually and collectively, and the findings are use
to improve the following year’s exam.
 
 
Scoring the Exam
Who Scores the AP Computer Science A
Exam?
The multiple-choice answer sheets are machine scored.
‘The teachers who score the free-response section of the
AP Computer Science A Exam are known as Readers. The
majority of these Readers are experienced faculty member> teach either alhigh school AP Computer Science A
se or an equivalent course ata college or university,
fat care is taken to obtain a broad and balanced group of
sders. Among the factors considered before appointing
aeone to the role are school locale and setting (urban,
al, and so on), as well as the potential Reader's gender,
nicity, and years of teaching experience. University and
h school computer science teachers who are interested
plying to be a Reader at a future AP Reading can
aplete and submit an online application via AP Central
centsal.collegeboard,com/readers) or request more
ormation by e-mailing apreader@ets.org,
1 June 2009, approximately 130 computer science
:hers and professors gathered at the Duke Energy Center
Zincinnati, Ohio, to participate in the scoring session
the AP Computer Science A Exam. Some of the most
rienced members of this group were invited to serve as
estion Leaders and Table Leaders, and they arrived at the
ding early to help prepare for the scoring session. The
raining Readers were divided into groups, with each
up advised and supervised by a Table Leader. Under the
dance of the Chief Reader, Question Leaders and Table
ders assisted in establishing scoring guidelines, selecting
aple student responses that exemplified the guidelines,
\ preparing for Reader training. All ofthe free-response
stions on the 2009 AP Computer Science A Exam were
uated by the Readers at this single, central scoring
sion under the supervision of the Chief Reader.
suring Accuracy
primary goal of the scoring process is to have all
ders score their sets of responses fairly, consistently, and
h the same guidelines as the other Readers, This goal is,
jeved through the creation of detailed scoring guidelines,
thorough training ofall Readers, and the various checks
balances that are applied throughout the AP Reading.
'w the Scoring Guidelines Are Created
‘As the questions are being developed and reviewed, the
Development Committee and the Chief Reader discuss
the scoring of the free-response questions to ensure that
che questions can be scored validly and reliably. Before
the AP Reading, the Chief Reader prepares a draft of the
scoring guidelines for each free-response question. In the
case of AP Computer Science A, a 10-point scale (0-9) is
used. A score of 0 means the student received no credit
forthe problem.
The Chief Reader, Fxam Leaders, Question Leaders, Table
Leaders, and ETS Assessment Specialists meet atthe
Reading site afew days before the Reading begins. They
discuss, review, and revise the draft scoring guidelines,
and test them by pre-scoring randomly selected student
responses. If problems or ambiguities become apparent,
the scoring guidelines are revised and refined until a final
consensus is reached,
3. Once the scoring of student responses begins, no changes
‘or modifications in the guidelines are made. Given the
expertise of the Chief Reader and the analysis of many
student responses by Question Leaders and Table Leaders
in the pre-Reading period, these guidelines can be used to
cover the whole range of student responses. Each
Question Leader and Table Leader devotes a great deal of
time and effort during the fist day of the Reading to
‘eeching the scoring guidelines for that particular question
and to ensuring that everyone evaluating responses for
that question understands the scoring guidelines and can
apply them reliably.
 
 
 
Training Readers to Apply the Scoring
Guidelines
Because Reader training is so vital in ensuring that students
receive an AP score that accurately reflects their performance,
the process is thorough:
1. nthe first day of the Reading, the Chief Reader provides,
an overview of the exam and the scoting process to the
entire group of Readers. The Readers then break into
sinaller groups, with each group working on a particular
question for which it receives specific training.
2. Question Leaders direct a discussion of the assigned
question, commenting on the question requirements and
student performance expectations. The scoring guidelines
for the question are explained and discussed.
3. The Readers are trained to apply the scoring guidelines
by reading and evaluating samples of student answers
that were selected at the pre-Reading session as clear
examples of the various score points and the kinds of
responses Readers are likely to encounter. Question and
‘Table Leaders explain why the responses received
particular scores
4, When the Question Leader is convinced the Readers
understand the scoring guidelines and can apply them
uniformly, the scoring of student responses begins.
Reading teams are formed by pairing a more experienced
Reader with a new or less experienced Reader. Each team
is given a set of student exams to score. Both members
of the team score each studert response independently.
The resulting scores and differences in judgment ate
discussed until agreement is reached, with the Table
Leader, Question Leader, or Chief Reader acting as
arbitrator when needed5. After a team shows consistent agreement on its scores, its
members proceed to score papers individually. Readers
are encouraged to seek advice from each other, the Table
Leader, Question Leader, or Chief Reader when in doubt
about a score. Throughout the course of the Reading, a
student response that is problematic or inappropriate
receives multiple readings and evaluations.
Maintaining the Scoring Guidelines
‘Throughout the Reading, Table Leaders continue to reinforce
the use of the scoring guidelines by asking their groups to
review sample responses that have already been discussed as.
clear examples of particular scores, or to score new samples
and discuss those scores with them. This procedure helps
the Readers adhere to the standards of the group and helps
to ensure thata student response will get the same score
whether itis evaluated at the beginning, middle, or end of
the Reading
‘A potential problem is that a Reader could unintentionally
score a student response higher or lower than it deserves
because that same student performed well or poorly on
other questions. The following steps are taken to prevent
this so-called halo effect
A different Reader scores each question and the student's
identity is unknown to the Reader. Thus, each Reader
can evaluate student responses without being prejudiced
by knowledge about individual students.
No marks of any kind are made on the students’ papers.
‘The Readers record the scores on a form that is identified
only by the students AP number. Readers are unable to
see the scores that have been given to other responses in
the exam booklet.
Here are some other methods that help ensure that
everyone is adhering closely to the scoring guidelines:
Table Leaders backread (reread) a portion of the student
responses from each of the Readers in that Leader's group
“This approach allows Table Leaders to guide their Readers
toward appropriate and consistent interpretations of the
scoring guidelines
Readers are paired, so that every Reader has a partner
with whom to check for consistency and to discuss
problem cases. Table Leaders and Question Leaders are
also paired up to help each other on questionable calls.
‘The Chief Reader and the Exam Leaders monitor use
of the full range of the scoring scale for the group and
for each Reader by checking data on score distributions,
and they randomly read selected papers to check for
scoring consistency.
Reliability data are periodically collected by having
Readers unknowingly rescore booklets. Scores resultin
from the first and second readings are then compared
and analyzed.
Preparing Students for the Exam
‘The AP Computer Science A course is designed to be
comparable to a typical introductory computer science
course taught in a college ot university department of
computer science. The course emphasizes object-oriented
programming methodology with an emphasis on problen
solving and algorithm development, and is meant to be th
equivalent of a first-semester course in computer science.
also includes the study of data structures and abstraction
For allist of the topics covered, see the topic outline in the
AP Computer Science A Course Description. The following,
goals apply to the AP Computer Science A course:
Students should be able to design and implement
solutions to problems by writing, running, and
debugging computer programs.
  
1% Students should be able to use and implement
commonly-used algorithms and data structures.
Students should be able to develop and select appropri
algorithms and data structures to solve problems,
Students should be able to code fluently in an object
oriented paradigm using the programming language
Java. Students are expected to be familiar with and be
able to use standard Java library classes from the
AP Java subset
= Students should be able to read and understand a large
program consisting of several classes and interacting
objects, Students should be able to read and understan
a description of the design and development process
leading to such a program, (An example of such a
program is the AP Computer Science Case Study.)
™ Students should recognize the ethical and social
implications of computer use.
As teachers focus on the above goals, they will not only be
preparing their students for the AP Computer Science A
Exam, they will be preparing them for future study and
applications of computer science
Essential Features of Student Responses
‘There is far more to computer science than just the syntax,
of a programming language. Similarly there is much mon.
to the exam than testing syntax. Student responses are
evaluated as “good first drafts’ of the solution to a probler
In a world where so many students (as well as professionaputer scientists) use tools such as IDEs to help in their
gramming, itis foolish to expect students to worry about
ing punctuation exactly right. As part of evaluating
-response questions, Readers are provided with General
ring Guidelines that describe how to penalize (or ignore)
vor errors, such as missing braces, confusing = and
using a class name as an instance of that class. In
ring questions, Readers focus more on whether a
Jent response adequately addresses the major issues of
question (for example, array access, looping, class
aipulation, etc.) than more minor issues (is the code
amented, are the braces aligned, are parentheses used
ead of brackets, etc.)
Additionally, the ability of students in college classes is
sssed by programming projects as well as test questions.
ay professors consider programming projects lo be more
vortant than test questions because they are more repre-
tative of how computer science is actually done. Since
‘Computer Science A students are assessed with only
questions, these questions may have more structure
1 those on a college test. For example, students on @
ege test may be asked simply to write code to determine
xe values in an array are in increasing order. Instead
‘omething so straightforward, a question on the
Computer Science A Exam may pose the problem as
ting code to determine if a student’ scores have im-
ved over the course of a term, where the scores are kept
narray. This more complicated question can then assess
tudents can do basic array manipulation and how they
ald perform on programming projects.
 
‘Teaching Free-Response Writing
It is important for teachers to devote some course time
to having students answer questions like those on the
free-response section in a timed environment. Students,
accustomed to doing all their work in IDEs may have
trouble writing code “from scratch.” Itis also important
to have students experience the challenge of reading a
description of a problem and understanding exactly what
is being asked in the problem. Often, students are asked to
use code for which they are given just an interface, not a
complete implementation. They need to have experience
with reading descriptions of code before taking the AP
Exam
Many successful AP Computer Science A teachers use
«questions from past free-response exams on a regular basis,
and go over the scoring in class. The most recent questions,
along with the scoring guidelines used, are available on
AP Centralvyhapter IT: The 2009
\P Computer Science A Exam
 
 
sxam Content and Format Giving a Practice Exam
Siving a Practice Exam “The following pages contain the instructions as they appeared
structions for Administering the Exam in the 2009 AP Examination Instructions for administering
ote the AP Computer Science A Exam. Following these
. instructions are a blank 2009 answer sheet and the 2009
the Exam AP Computer Science A Exam, If you plan to use this,
released exam to test your students, you may wish to use
:am Content and Format these instructions to create an exam situation that closely
2009 AP Computer Science A Exam is 3 hours in length resembles an actual administration. If so, read only the
haas two sections: indented, boldface directions to the students all other
Instructions are for the person administering the exam and
need not be read aloud, Some instructions, such as those
referring to the date, the time, and page numbers, are no
longer relevant and should be ignored. References to the
AP Computer Science AB Exam, which was discontinued
after the 2009 administration, should also be ignored.
‘The term “grades,” which appears in the exam and exam
instructions that follow, refers to AP Exam scores of 1, 2,3,
4,0r5.
Another publication you might find useful is the
Packet of 10—ten copies of the 2009 AP Computer
Science A Exam, each with a blank answer sheet. You
can order this ttle online at the College Board Store
(store.collegeboard.com).
\ 75-minute multiple-choice section consisting of
\0 questions accounting for 50 percent of the final score.
4 105-minute frée-response section consisting of
i questions accounting for 50 percent of the final score.
 
    
    
 
2009 AP Computer Science A
Exam Format
Multiple Choice (Section I)
40 questions .... -75 minutes
  
Free Response (Section I)
4 questions veeceeseees 105 minutesInstructions for Administering the Exam
(from the 2009 AP Examination Instructions booklet)
‘The Computer Science A exam and the Computer Science AB exam should be administered
simultaneously. They may be administered in separate rooms, or in the same room if it is more
convenient.
SECTION I: Multiple-Choice Questions
J[ Do not begin the exam instructions below until you have completed the appropriate
General Instructions for your group.
 
Make sure you begin the exam at the designated time. When you have completed the General
Instructions, say:
Itis Tuesday morning, May 5, and you will be taking either the AP Computer
Science A Exam or the AP Computer Science AB Exam. {na moment, you will
open the packet that contains your exam materials. By opening this packet,
you agree to all of the AP Program's policies and procedures outlined in the
2008-09 Bulletin for AP Students and Parents. Please check to make sure you
have the correct exam: Computer Science A or Computer Science AB. Raise
your hand if you do not have the correct exam.
 
You may now apen your exam packet and take out the Section | booklet, but
do not open the booklet or the shrinkwrapped Section II materials. Put the
white seals aside. Read the statements on the front cover of Section | and
look up when you have finished. .. .
Now sign your name and write today's date. Look up when you have
finished. ...
Now print your full legal name where
 
icated. Are there any questions? ..
‘Answer any questions. Then say:
Now turn to the back cover and read it completely. Look up when you
have finished. .
  
Are there any questions?
‘Answer any questions. Then say:
Section | is the multiple-choice portion of the exam. You may never discuss
these multiple-choice questions at any time in any form with anyone,
including your teacher and other students. If you disclose these questions
through any means, your AP Exam grade will be canceled. Are there any
questions? .
 
 
Answer any questions. Then say:
You must complete the answer sheet using a No. 2 pencil only. Mark
all of your responses on your answer sheet, one response per question.
Completely fill in the ovals. There are more answer ovals on the answer
sheet than there are questions, so you will have unused ovals when you
reach the end. Your answer sheet will be scored by machine; any stray marksor smudges could be read as answers. If you need to erase, do so carefully
and completely. No credit will be given for anything written in the exam
booklet. Scratch paper is not allowed, but you may use the margins or any
blank space in the exam booklet for scratch work. Are there any questions? . ..
 
Answer all questions regarding procedure, Then say:
You may use the orange appendix booklet throughout the exam. Appendix A
contains the AP Java Quick Reference, and appendixes B through G contain
case study reference material. In the Computer Science A exam, the case study
questions are 21 through 25. In the Computer Science AB exam, the case study
questions are 20 through 25. You have 1 hour and 15 minutes for Section I.
Open your Section | booklet now and begin.
® Note start Time here____ Note Stop Time here ____.. You and your proctors
should make sure students are marking their answers in pencil on their answer sheets, and that
they are not looking at their shrinkwrapped Section II booklets. After 1 hour and 15 minutes, say:
 
 
‘Stop working. Close both your exam booktet and orange appendix booklet
and put your answer sheet on your desk, face up. | will now collect your
answer sheet.
‘After you have collected an answer sheet from each student, say
Take your seals and press one on each area of your exam booklet marked
“PLACE SEAL HERE.” Fold them over the open edges and press them to the
back cover. When you have finished, place the exam booklet on your desk
with the cover face up. Keep your orange appendix booklet; you will need it
for Section II of the exam.
 
I will now collect your Section | booklet.
{As you collect the sealed Section 1 booklets, check to be sure that each student has signed the
front cover. There is a 10-minute break between Sections | and I. When all Section I materials
have been collected and accounted for and you are ready for the break, say:
Please listen carefully to these instructions before we take a break.
Everything you placed under your chair at the beginning of the exam must
remain there. You are not allowed to consult teachers, other students,
or textbooks about the exam materials during the break. You may not
make phone calls, send text messages, check e-mail, access a computer,
calculator, cell phone, PDA, MP3 player, e-mail/messaging device, or any
other electronic or communication device. Remember, you are not allowed
to discuss the multiple-choice section of this exam with anyone at any time.
Failure to adhere to any of these rules could result in cancellation of your
grade. Please leave your shrinkwrapped Section II package and your orange
appendix booklet on top of your desk during the break. You may get up, talk,
go to the restroom, or get a drink. Are there any questions? ...
 
Answer all questions regarding procedure. Then say:
@® Let's bogin our break. Testing will resume atSECTION II: Free-Response Questions
After the break, say
May | have everyone's attention? Place your Student Pack on your desk. ...
You may now open the shrinkwrapped Section Il package. ...
Read the bulleted statements on the front cover of the pink booklet. Look up
when you have finished. ...
Now place an AP number label on the shaded box. If you don't place an
‘AP number label on this box, it may be impossible to identify your booklet,
which could delay or jeopardize your AP grade. If you don’t have any AP
number labels, write your AP number in the box. Look up when you have
finished. ..
 
   
 
Read the last statement... .
 
9 a pen with black or dark blue ink, print the first, middle, and last
Is of your legal name in the boxes and print today's date where
‘ated. This constitutes your signature and your agreement to the
conditions stated on the front cover... .
  
‘Tum to the back cover and read Item 1 under “Important Identification
Information.” Print your identification information in the boxes. Note that
you must print the first two letters of your last name and the first letter of
your first name. Look up when you have finished. .
In {tem 2, print your date of birth in the boxes... .
Read Item 3 and copy the school code you printed on the front of your
‘Student Pack into the boxes. ...
Read Item 4. .
Are there any questions? . . .
Answer all questions regarding procedure. Then say:
I need to collect the Student Pack from anyone who will be taking another
‘AP Exam. If you are taking another AP Exam, put your Student Pack on your
desk. You may keep it only if you are not taking any other AP Exams this
year. If you have no other AP Exams to take, place your Student Pack under
your chair now. ...
While Student Packs are being collected, read the “At a Glance” column.
and the instructions for Section Il on the back cover of the pink booklet.
Do not open the booklet until you are told to do so. Look up when you
have finished. . ..
  
Collect the Student Packs. Then say:
Are there any questions? . . .
Answer all questions regarding procedure. Then say:
 
Now open the Section II booklet and tear out the green insert that is in the
center of the booklet. In the upper right-hand corner of the cover, print your
name, your teacher's name, and your school’s name.Read the information on the front cover of the green insert. Look up when
you have finishe
 
‘You will need the orange appendix booklet for Question 2 in both the A exam
and the AB exam, although you may use it at any time during this period. You
may make nates in the green insert, but you must write your answers in the pink
booklet using a No. 2 pencil. You are responsible for pacing yourself, and may
proceed freely from one question to the next. If you need more paper during the
exam, raise your hand, At the top of each extra piece of paper you use, be sure to
write your AP number and the number of the question you are working on. You
have 1 hour and 45 minutes for Section Il. Are there any questions? ....
 
  
Answer any questions. Then say:
You may begin.
@ Note start Time here Note Stop Time here __. You and your proctors
should make sure students are writing their answers in their Section IT booklets, After I hour and
35 minutes, say:
 
There are 10 minutes remaining.
After 10 minutes, say:
‘Stop working and close your exam booklet, the orange appendix booklet, and
the green insert. Put your pink booklet, your orange appendix booklet, and
your green insert on your desk, face up. Remain in your seat, without talking,
while the exam materials ate collected... .
 
Collect a pink Section II booklet, an orange appendix booklet, and a green insert from every
student. Check for the following:
+ Section II booklet front cover: The student placed an AP number label in the shaded box,
and printed his or her initials and today’s date
+ Section II booklet back cover: The student completed the “Important Identification
Information” area.
+ ‘The student wrote answers in the pink booklet and not in the orange appendix booklet or
green insert.
‘The green inserts must be stored securely for no fewer than two school days. After the two-day
holding time, the green inserts may be given to the appropriate AP teacher(s) for return to the
students. The orange appendix booklets must be returned to the AP Program. When all exam
materials have been collected and accounted for, say’
 
Your teacher will return your green inserts to you in about two days, You
may not discuss the free-response questions with anyone until that time.
Remember that the multiple-choice questions may never be discussed or
shared in any way at any time. You should receive your grade report in the
mail about the third week of July. You are now dismissed.
 
 
Exam materials should be put in locked storage until they are returned to the AP Program after
your school’s last administration, Before storing materials, check your list of students who are
eligible for fee reductions and fill in the appropriate oval on their registration answer sheets. To
receive a separate AP Instructional Planning Report or student grade roster for each AP class
taught, fill in the appropriate ova} in the “School Use Only” section of the answer sheet. See “Post-
Exam Activities” in the 2009 AP Coordinator's Manual
u5 fi ces eons cows in
Be g jeosesesces]| | | : w |§9] leseseadess,
|g 5 jooeeoesoes| Ha 2,|80| jeoasoaecce
2/82 |B [EE leccoooscee Hil 2| g8[ge]_Jeoseoeeces
° |e G 3 E ]OS20G8S000! iH FF Oo) | |do| |scasesaone!|
i : =
A FH 8H) Jecossoeses) ET, Hits 1
2 ae 8g | “oousecsces| hl Seal AL uk
Ree Ey S) CEPI HER ale uu
E Be 5° | Jesssonaees 285) ||P GF olf fia
& é & ff 3 | Teosseecoes Seaa|” 28588 “lz ana
g Se ooveenecse| ' r He
bas
i ge —Jessswseoas) | § Hy
es E [| Jeconsescce bo 2 ie un
3 B]y decssesoses| |, £ | Bl 2 is 2858
5 5|:| “sce Bed § |B) § |g|B cooccocce
& 5 gle] 228222323 5 2:8 2 7
gli] coooaséss. e¢ | il 2
Fae rleeeeeeeeeles) FIVE (| Al fy] Mecocccoss
i 3 Elegy |i) oF
@ ls = 523 ig|_ 2 i] seseoseses|
. i a 2 Be Sei es| 1/233] |2| [ecocosesce
% $) 3: seg £2322) |E/B22| |3| Jeososcssse
© 5 Se |5 e800) 6 oma |§| [@S8ODGO5S9)
g 5] lscoecoenee|
8 jsoascesoed ide i] “jeceossssoo
& 2eeeoaeoeq New Fi |SSeS0088SS)
2 [Jecsossooes| 3] jeseesoesen,
23 H Soesesese: §) leceesesees!
ey lecsaeseced] _BS88558565) 1 _leceoosaces
Eecseosseed |g ease ia
- § |[ecssccene: ay SOSSSSSSSS!
Soeecescealaalla ay Sossensone
a[ |sececsanccccsnaccsscsseses | | *f| lecssnesces
}POVSHHHDSHISIDSOGHOSHDSHIOSOSVOO —
(ea0de0escosSsZeseDeosOSeoNd| ae i
| jsseascescoaonasonnaosoneons] | | §2 fF
g joaaocncccassaT0D0505000000: soeel F |
3 {\Jeecns002000000050080590089: He
= 3 | ]sessececosesrsosss05cos005: 2228352 i
é 1 Josocececconaacnssns5sose0s: oOo 2CCO
gl } (SHOHOGODHSOSOISSOSOSOOISSSSOG| |F SRB588R i
2g 3| Jesscecencseos0ss0900s920090] | jf 3 '
2 i[jesesscescsesessncsaccs20500] |; 11 shoes |
3 {| [eevescoccoasscencsaosues0—0) [75 py a gsbhee
2 al } [ Tossescwnoseosanseoaosooo—00 |y|! 5 7 $3 gegeees
22 }| [lesoescecovecasccenscsnssoe || |Fiiripapigaziee)
EB }| [Jesaoscasccssnsoncenosonanaale| |p begtices se 021225
24 || [[sssescssasacssscsccscsane # PoP
5 gz z [SBOQSSOVSOIVTSSOOHSSHOOIOSHSSOS| goo IODOOSSCOSSO}
26) 5| | Josenscnqcesoncssncesssceoen|2| [2 Peaaanasssssesee
x eaoncoemosecsras2cess9e2000) «| |!
a alee Sescesecosoascassscosososec|| |f ;
Beleay {| Jewenecsaocesssca0seses20500 3) |ice off E82 5 ft
Bey Ssossenscososssssenssseasse @| | {i eff ig
Pe i Jescesssocoossssecooscseeses|f| |FEf Foe 3} qu BE
2 BI GU ry [§]}| lesseseecocoossccsenoscooosold| | Phage plrsebhdl
o Sle! [2] £|:| losanenanccaaez0nsmscsasenea|s|f | 223727 Pine peae
e2!U |) 2|}| lecosccesosccsnsaccosossoe0|§) | 39% a BREESE
21121 8| §|; Jecaasnancseaassmacscsoseoss || SscqasesNs50N009
225124 9| 3|!—saonascaccassaaameascosaae | «i | SSETFERRRASABESS
 
 
 
 
 
 
 
 
 
 
SoePAGE 2
(GotegoBoard AP
 
RThis section is for the survey questions in the AP Student Pack. (Do not put responses to exam
‘quostions In this section.) Be sure each mark is dark and completely fils the oval.
 
1@@QODOGO
2@®OOOGOO
3 @a@
 
 
 
 
Language and Culture, Japanese Language and Culture,
following questions. (Your responses wit not alc your grad)
“Have you ved or stdied for one month or more in a county where the
language ofthe exam you are now aking is spoken? Ov ON
2, Do you reguaty speak or hear he language at home? Owe OM
 
 
 
Indicate your answers to the exam questions In this section. Ifa question has only four answer options, do
‘not mark option E. Your answer sheet will be scored by machine. Use only No. 2 pencils to mark your
answers on pages 2 and 3 (one response per question}. After you have determined your response, be sure
to completely fil|n the oval corresponding to the number of the question you are answering. Stray marks.
and smudges could be read as answers, $0 erase carefully and completely. Any improper griddi
affect your grade. Answers written in the multiple-choice booklet will nt be scored.
 
 
 
1®OQOCO ezDOOOe 31 @OOOO
PRCRORGRORG) 7@P®BOOG 2 BOOOG
3®@®@OOO 32 @OOOG 3 ®@GDOOO
1@OOOO 2 @OOOO 4 @OOOG
5®@OoOOO »@OOCOG 53 DOOCOG
s®OOOO 31 @@OOG 5 @DOGO
7®@@2OOO 2@®OOO 7 @®OOO
s®@®OOO@ 3 @®@®OOO 3 @®GOOO
2D®OOO x @®DOOO 3 @GBOOO
0 @OOOO 3s @OOCOO 2 ®@®OCOO
1 @®OOO OOOO 1 ®@OOOG
2@GCOeG 7 QDOOG 2 ®DOOOO
3 @®OCOO w@DOOOO aD®OOe
u®@®DOOO »@®OOO #2DOOG
5 ®@OOOO 0 ®@®©CO® 5s ®OOCOO
6 @®DOOO 1 @®@GOG ®D@OOOO
7 @®OOO 2@®OOO DRCRCRCRORG)
Bw ®®DOO 03 @OOO® 8 ®@OOCO
1 @OOOO “#@®®OOCO® 8 BOOOO
n@OOCOO 6 ®DOOO n®®OOO
2 @GOO® #6 ®OOOO 1@®@OCOG
2@OOO®O 7 ®@®QOOO 2z@OOOO
232 @QODO #2 @ODOOO B@BOOOO
2 @O®OOO 2@®COO u@®COO
ER ORORCRORG) »®@OCOG B@2OoCoO
 
FOR QUESTIONS 76-151, SEE PAGE.
 
DO NOTWRITE INTHIS AREA.PAGES
 
(GottegeBoara AP
0900909090000 0080099008000
0000060000000 00H0000000000
0000000000000 H0HHHHHH9HOOO
020000000000 000H0099000000
00090000000009988900000000
HERSSSSSSSESSSTIITLSTLLIE
 
 
 
090090009800 0990809800900
00009000 0600089H800080000
0009000 90GHHHHHHHOHOQOHOO
 
00008900000 H0O90GO0000008
0000908808 0000008OH0E6800
SYSSSSESSSSHSELSSLASTAR SH
ETSUSE ONLY
 
 
 
DO NOT WRITE INTHIS AREA.
 
 
000000800 9090900H000990000
009000600000 980H800009900
000900009090 90H99H0990008
0000 000000900000000080800
09000980009 09089090880900
SERRSSSLSBSSSSRSHFSHRSRRS
', do not mark option E.
 
 
Be sure each mark is dark and completaly fils the oval. I a question has only four answer
opti
 
 
 
TOTAL
 
 
 
omen
 
14serrata gern i A
  
HOME ADDRESS AND SCH:
 
meg
   
“7 YOUR MAILING ADDRESS.
4 oscesoeo
SSSSSSESS
jooooeoece® Lie
 
 
OR POSTAT
SensasenooasszoSTse5soa008
Tpevsesencoaas20enpesone008
Tpecosesscoss20022scs0c000
Teeneecoscoscszewage0o0re59
sa0onceTcoesaToDTeeseaee5o
“peocosesconcs200ceqcos0009
SASSSODSOSESD9STHSS99z900
jomooseosco22a2200096092009
seaoeoacosco2s000090002020
 
(S008000608
eseses85009)
sosessesees|
20909900089
S5OSGSSSO55|
eceseoe5ees|
ecescsssees!
@eeeceeeseso
soesncesos
 
 
“Cage Name ard rose
 
.
 
‘Saag
 
 
 
  
"TELEPHONE.
ay
al t
‘WTERWATIONAL
 
 
BSSSSOSSSSSSSOSSSSOGSDSSS|
PvSSOODOGsSoDPIOENNES000008]
SHSESODOSSTSEOOIDSEQSS=z09
SOO900208S09080000352008)
@EGOSOSSS9SS000E90902008)
@DGES0SESOS2DO000OOI2S008|
e2eeooncoesso200000G92208
POVQooDSSSoSSOH0SeEs92008
\@DOSSSHSOSISSOGLDGOIDSE08|
©83O20S060228T000008998008
@OSSS2COSEZSDSSEC0R9RE9)
PBSSSADSSSISTIOOHSSODECSA
 
Possesesas|
SSSSSSSSG|
BSSOSS0S|
“possessoos|
SOSSSSSSS|
jscssoeescs!
(Beeeoeases|
SHSSSOSSS
jsoseooesoo|
posnessese|
» pwauatose
 
 
 
 
 
 
 
 
 
 
‘V-COLLEGE TO RECEIVE YOUR AP GRADE REPORT
Coleg Case]
 
SESSSSSSSS}
ecosocscee),
ecaseesees|
@090000000
 
 
School Nae, Oly and Se
ave catty ener your
ake sr
‘adn te spbenriai Sa
BS in rormaon bole
a
oa
 
 
 
 
SOO 9SO0SGS92200T090000000
 
 
 
 
 
[ear
SOODSSDSSSSSTOOOSSOSSSSHO
POOGODSCOSESSDSESE0R00009
©O0GHODOSO22008090022009
SOOSHODSOVIDEOOTHBOCDESOO
PEOSSoDSSTSSzOSGNs0C0RS09
PODQSODOSOSSEIOLSSODOSSOO
POOSSHSCOSODDOSODASOIESEOO
SOBSHETOSSOTISOOOSOSESE0e
2ODLHOSOS@OSOSOOSIOSOSSOO
IOOSSHSOSSOSSOGSOSSOIGOIOS
@OSOOBQOSSTSONHIDSESED000
@OSSOSEOOOOAOTOSTSODS2EO0S
POSSHODIGSODSOSOOSCOSESOR
POSOS92OHI229008980SS209
©2S2OGQ06E090002000002000
SOTOSADSSOIDSSOLOOOSISS08
}@OC@SEDSSSIATABOSOSISSOR
POdSSODDOSEZEDOBESSSOSEES
PO2SSODSOSISIGONLOSSSSOOS
OLOGOOHOSSOSSOSTSSOISSSES
\SBOSDODOOSESOOSIESOOSNSON
OVOSSOSCGOOSSE®OOBOOOSTSOS:
POSSHO2VOLIDDOOSHOSOBOZOH
POB@SODSOLHDOOSHODESSEOS
2BOSSODSOOODEDESSSOSSOOOS
2OOUOODOGHOTOOHISSOGSSSOO
SSSSOSSSSS
eoesceeeeso|
eoeeeeesess|
eonecesoses|
eoeceossoed|
eo0esces00s0)
@0800980089
soeecsesees|
eeseese009)
@eeeseoses0)
e0a0e08sess)
eoe0esese00|
eosesceeees
@0900800089|
ecaesseseee!
@0090005080
ece2esesees]
eoseseesess|
seseseseees|
@ee2o220e00
eoeseeesess|
eoeseesseso|
e0esese0ee)
soseeoswwsc|
eoesessceso|
eo00ea2080
X-SCHOOL YOU ATTEND
School Cade
pti tii |<
 
SSSSSSSSSS
@080000800
ecese0ase0)
eceseccee0
eceeseeeso)
2089200088
 
 
 
 
orgie enough or delay
"Fon STOOENTS OUTSIDETWE UNTTED STATES ONGY
 
 
 
 
 
 
 
.The Exam
AP* Computer Science A Exam
2009
DO NOT OPEN THIS BOOKLET UNTIL YOU ARE TOLD TO DO SO.
Total Time
‘hour, 15 minutes
Number of Questions
40
Percont of Total Grade
50%,
Writing instrument
Pencil required
Electronic Device
None allowed
 
Instructions
Te orange Appendix booklet i provided for use in both Section I and Section I
Section I of this exam contains 40 multiple-choice questions. Fil in only the ovals for
‘numbers | through 40 on your answer sheet
Indicate all of your answers to the multiple-choice questions on the answer sheet. No
credit wil be given for anything written in this exam booklet, but you may use the booklet
for notes or scratch work. After you have decided which of the suggested answers is best
completely fill in the corresponding oval on the answer sheet. Give only one answer to
each question. If you change an answer, be sure that the previous mark is erased
‘completely. Here is 2 sample question and answer.
Sample Question, Sample Answer
Chicago isa ®eooeo
(A) state
(B) city
(© country
(D) continent
(&) village
Use your time effectively, working as quickly as you can without losing accuracy. Do not
spend too much time on any one question. Go on to other questions and come back to
the ones you have not answered if you have time. It $ not expected that everyone will
know the answers to all ofthe multiple-choice questions
About Guessing
Many students worcer whether or not to guess the answers to questions about which they
are not certain. in this section of the examn, asa correction for random guessing
‘one-fourth of the number of questions you answer incorrectly will be subtracted from the
number of questions you answer cosrecty. Ifyou are nat sure ofthe best answer but have
some knowledge of the question and are able to eliminate one or more of the answer
choices, your chance of answering correctly is improved, and it may be to your advantage
to answer such a question,
qw18
‘COMPUTER SCIENCE A
SECTION I
‘Time—I hour and 15 minutes
Number of questions—40
Percent of total grade—S0
Directions: Determine the answer to each of the following questions or incomplete statements, using the available
space for any necessary scratch work. Then decide which is the best of the choices given and fill in the corresponding
oval on the answer sheet. No credit will be given for anything written in the examination booklet. Do not spend 100
much time on any one problem.
Notes:
«Assume that the classes listed in the Quick Reference found in the Appendix have been imported where
appropriate
‘+ Assume that declarations of variables and methods appear within the context of an enclosing class.
‘+ Assume that method calls that are not prefixed with an object or class name and are not shown within a complete
class definition appear within the context of an enclosing class.
‘+ Unless otherwise noted in the question, assume that parameters in method calls are not nul.
 
Unauthorized copying o une a]
[ny patel in pe eset GO ON TO THE NEXT PAG!1. Consider the following code segment.
int value = 15;
while (value < 28)
{
System.out .print1n(value) ;
value++;
y
What are the first and last numbers output by the code segment?
 
Est Last
(a) 15 oa]
(B) 15 28
©) 16 a
(D) 16 8
(16 29
 
 
GO ON TO THE NEXT PAGE. 192. A teacher put three bonus questions on a test and awarded 5 extra points to anyone who answered all three
bonus questions correctly and no extra points otherwise. Assume that the boolean variables bonusOne,
bonusTwo, and bonusThree indicate whether a student has answered the particular question correctly.
Each variable was assigned true if the answer was correct and false if the answer was incorrect.
Which of the following code segments will properly update the variable grade based on a student's,
performance on the bonus questions?
 
if (bonusOne && bonusTwo && bonusThree)
grade += 5;
I if (bonusOne || bonustwo || bonusThree)
grade += 5;
II if (bonusone)
grade += 5
if (bonustwo
grade += 5;
if (bonusThree)
grade += 5;
 
(A) Lonly
(B) Monly
(C) Monly
(D) Land IL
(B) Wend UL
 
sathorined copying oF
20 ny part of his pape eg
  
 
GO ON TO THE NEXT PAGE‘Assume that an array of integer values has been declared as follows and has been initialized.
int{] arr = new int{10};
Which of the following code segments correctly interchanges the value of arr (0] and arr{5] ?
 
(A) arr[0] = 53
arr[5] = 0;
(B) arr(0] = arr(s];
arr(5] = arr(0];
 
(© int k = arri5i;
arr(0) = arr(5];
arr[5] = k;
 
(D) int k = arr{o};
arr(Q] = arr(5];
arr(5] = k;
(B) int k = are{5];
arr(5] = arr(0];
arr(0) = arri5];
 
‘authori coping or eave al]
pet of this page aga
 
GO ON TO THE NEXT PAGE. a22,
4,
 
Consider the following code segment.
ArrayList
 items = new ArrayList();
items .add("A\
itens.
items. fi
items.add(0, "D*);
items. remove (3):
items.add(0, "E");
System.out .print1n (items) ;
   
What is printed as 2 result of executing the code segment?
(A) 1A, B,C, El
(B) (A, B, D, B}
© [£, D, a, BY
(0) [z, D, a, C}
(©) (8, D, C, B)
 
When designing a class hierarchy, which ofthe following should be true of a superclass?
(A) A superclass should contain the data and functionality that are common to all subclasses that inherit from
the superclass.
(B) A superclass should be the largest, most complex class from which all other subclasses are derived.
(C) A superclass should contain the data and functionality that are only required for the most complex class.
(D) A superclass should have public data in order to provide access for the entire class hierarchy.
(E) A superclass should contain the most specific details of the class hierarchy.
 
 
GO ON TO THE NEXT PAGE.Questions 6-7 refer to the following code segment.
int k = arandom number such that 1S Sn;
for (int p = 2; p <= k; p++)
for (int r= 1; r < ki r+)
System.out.print1n("Hello");
 
6. What is the minimum number of times that He110_ will be printed?
(a) 0
Bt
©2
(D) n=!
©) 1-2
 
 
7, What is the maximum number of times that Heo will be printed?
(A) 2
 
Satoriged copying orreue ol]
oft page eae.
 
 
GO ON TO THE NEXT PAGE.
23“8, Consider the following instance variable and incomplete method. The method calcTotal is intended to
~ return the sum of all values in vals.
private int(] vals;
 
public int caleTotal()
{
int total = 0
 
/* missing code */
return total;
}
Which of the code segments shown below can be used to replace /* missing code */ sothat
calcTotal will work as intended?
L for (int pos = 0; pos < vals.length; post+)
{
total
)
 
vals{pos]
I. for (int pos = vals.length; pos > 0; pos
(
total
}
 
 
vals{pos];
I. int pos = 0;
while (pos < vals. length)
{
total
post+
)
 
vals{pos];
(A) Lonly
(B) only
(C) Monty
(D) Land ttl
(E) Wand I
 
 
 
 
24
 
GO ON TO THE NEXT PAG!). Consider the following code segment.
String str = ‘abcdef*;
for (int rep = 0; rep < str.length() - 1; rept+)
t
system. out print (str.substring(rep, rep + 2));
}
‘What is printed as a result of executing this code segment?
(A) abedet
(B) aabbecddeeté
(©) abbecddeet
(D) abebcdcdedet
 
is printed because an IndexOutOfBoundsExcept ion is thrown.
 
 
GO ON TO THE NEXT PAGE. 2526
10. Consider the following method.
public void numberCheck(int maxtum)
{
int typea = 0;
int types = 05
int typec = 0;
  
for
{
if
 
(int k= 1
 
maxNum;
(ka2
typeat+;
if Ue 82
typea++
if (k a5
typeC++
 
0 && kK 5 ==
 
 
0)
 
0
)
system.out-printInitypea + *
)
k++)
Cr)
“4 typen +"
What is printed as a result of the call numberCheck (50) ?
(A) 5
(B)
(C)
(D)5
©)
205
5 20 10
5255
25 10
30 25 10
 
 
[Unauthorzad copying o aus o]
any part of ts page legal
 
 
s+ typec) ;
GO ON TO THE NEXT PAG1. Consider the following method that is intended to modify its parameter nameList by replacing all
occurrences of name with newValue.
public void replace (ArrayList nameLi:
String name, String newvalue)
 
ce
for (int j = 0; 3 < nameLis!
t
size(); j++)
 
if ( /* expression */ )
{
nameList.set(j, newvalue) ;
}
)
)
Which of the following can be used to replace /* expression */ sothat replace will work
as intended?
(A) nameList get (5) .equals (name)
 
(B) nameList get (3)
(C) nameList .remove (4)
(D) nameList(j] == name
(BE) nameList [j}.equals (name)
\Siherzed copying or reuse of]
‘oar of ts pa
 
 
fringe GO ON TO THE NEXT PAGE.
a12, Consider the following incomplete method.
public int someProcess(int n)
t
/* body of someProcess */
)
‘The following table shows several examples of input values and the results that should be produced by calling
someProcess,
Input Value Value Returned by
 
 
 
n_someProcess (1)
3 30
6 ®
ee 7
Coe 80
9 |
u “a
pn | mo
14 u|
16 160
 
Which of the following code segments could be wsed to replace /* body of someProcess */ so that
the method will produce the results shown in the table?
Lif ((n 8 3 == 0) && (n & 4 == 0))
return n * 10;
else
return ni
 
IL if ((n & 3 == 0) |
return n * 10;
 
o)
 
return n;
 
[Grautosad coping a uae of
28 [any part of ts page fog
 
 
 
 
GO ON TO THE NEXT PAG!IL if @%3
if (n 8 4 == 0)
return n * 10;
 
 
return n;
A) Lonly
B) Monly
©) Monty
D) Land ft
E) Wand IM
 
 
GO ON TO THE NEXT PAGE. 2913. Consider the following method.
// precondition: x >= 0
public void mystery(int x)
i
if (x / 10) != 0)
(
mystery(x / 10);
)
 
System.out-print (x % 10);
)
Which of the following is printed as a result of the call mystery (123456) ?
(a) 16
(B) 56
(C) 123456
(D) 654321
(E) Many digits are printed due to infinite recursion.
 
[Unauthorend copying or eure of
[any part of bis pag egal
 
 
 
GO ON TO THE NEXT PAGConsider the following instance variables and incomplete method that are part of a class that represents an item.
‘The variables years and months are used to represent the age of the item, and the value for months
always between 0 and 11, inclusive. Method updateage is used to update these variables based on the
parameter extratonths that represents the number of months to be added to the age.
 
private int years;
private int months; // 0 <= months <= 11
// precondition: extraMonths >= 0
public void updateage(int extraMonths)
i
/* body of updateage */
)
Which of the following code segments could be used to replace /* body of updateage */ so thatthe
method will work as intended?”
1. int yrs = extraMonths % 12;
int mos = extraMonths / 12;
years = years + yrs;
months = months + mos;
Il, int totalMonths = years * 12 + months + extraMonths;
years = totalNonths / 12;
months = totalMonths % 12;
Ill. int totalNonths = months + extraMonths;
years = years + totalMonths / 12;
months = totalNonths % 12;
(A) Lonly
{B) Ioniy
(©) Mfonly
(D) Hand IIT only
(®) 1.1 and tt
 
 
GO ON TO THE NEXT PAGE.
at15, Consider the following method.
public String inRangeMessage(int value)
 
C
if (value <0 [| value > 100)
return "Not in range";
else
return "In range";
)
Consider the following code segments that could be used to replace the body of inKangeMessage.
1 if (value < 0)
{
if (value > 100)
return "Not in range";
else
return
In range";
)
else
yeturn "In range";
I. if, (value < 0)
return ‘Not in range";
else if (value > 100)
return "Not in range";
else
return ‘In range";
IM. if (value >= 0)
return "In range";
else if (value <= 100}
return "In range";
else
return "Not in range";
 
Which of the replacements will have the same behavior as the original version of inRangeMessage ?
(A) Lonly
(B) Honly
(C) Mtonly
(D) Land tt
(©) Wand 1
 
GO ON TO THE NEXT PAConsider the following class declaration.
public class SomeClass
{
private int num;
public SomeClass(int n)
{
num
)
 
public void increment(int more)
{
num = num + more;
)
public int getnum()
(
return num;
}
d
‘The following code segment appears in another class.
SomeClass one = new SomeClass(100);
SomeClass two = new SomeClass(100);
SomeClass three = one;
one. increment (200) ;
system.out.printIn(one.getNum() + * " + two.getNum() +" "+
three.getNum());
What is printed as a result of executing the code segment?
(A) 100 100 100
(B) 300 100 100
(© 300 100 300
(P) 300 300 100
(©) 300 300 300
 
 
GOON TO THE NFYT PAGE aa4
17. The following incomplete method is intended te sort its array parameter rx’ in increasing order.
// postcondition: arr is sorted in increasing order
public static void sortarray(int[] arr)
{
int 3, k;
for (j = arr.length - 1; j > 0;
{
int pos = j;
 
for ( /* missing code */ }
i
if (arr[k] > arr[pos])
{
pos = k
}
)
swap(arr, j, pos);
3
Assume that swap(arr, j, pos) exchanges the valuesof arr [4] and arc [pos]. Which of the
following could be used to replace /* missing code */ so that executing the code segment sorts the
values in array arr?
yk = 5-1; > 07 kee
 
 
 
(B) kK = 5-4; k >= 0; ke
(C)k = 1; & < arr.length; k++
(D) k = 1; k > arrlength; ke+
(BE) k = 0; k <= arr.length; k++
Grauthorized copy
ary part of tls page
 
GO ONTO THE NEXT PA‘{Assume that 2 and y are boolean variables and have been properly initialized.
(x 6& y) || 1Ge && y)
The result of evaluating the expression above is best described as
(A) always true
(B) always false
(©) true only when x is true and y is true
(D) true only when x and y have the same value
(2) true only when x and y have different values
 
 
GO ON TO THE NEXT PAGE. 3536
19, Assume that the following variable declarations have been made.
double @ = Math. random();
double x;
Which of the following assigns a value to
range 0.5 = 90)
return true;
if (testAverage
return true;
return false;
 
= 75 && assignmentsCompleted >= 4)
I, boolean pass = false;
if (testAverage >= 90)
pass = true;
if (testAverage >= 75 && assignmentsCompleted >= 4)
pass = true;
return pass;
Il, return (testaverage
(testaverage
90) ||
75 && assignmentsCompleted >= 4);
 
Which of the implementations will correctly implement method isPassing ?
(A) Lonly
(B) Honly
(©) Fand 11 only
(D) Hand UL only
(8) LU, and it
 
 
GO ON TO THE NEXT PAGE.
3738
 
Questions 21-25 refer to the code from the GridWorld case study. A copy of the code is provided in the
Appendix.
21. Consider the following code segment.
Location loch
Location loc2
 
new Location(3,
new Location(3,
i (1ocl equals (1oc2 .getadjacentLocation (Location. EAST) })
System. out.print ("aaa");
if (loc1.getRow()
if (loc. getDirectionToward(1oc2)
system. out .print ("555");
‘What will be printed as a result of executing the code segment?
(A) aaaxxx555
(B) aaaxxx
(C) xxx555
(D) 555
(B) aaa
= loc? .getRow())
System. out print ("XXX") ;
 
Location. EAST)
 
Unauhorzed copying ox ruse al
any part of is ge a toga
 
 
 
 
GO ON TO THE NEXT PAC1A RightTurningBug behaves like a Bug, except that when it turns, it turns 90 degrees to the right. The
declaration for the RightTurningBug class is as follows.
public class RightTurningBug extends Bug
(
public void turn()
/* missing implementation */
)
)
Consider the following suggested replacements for /* missing implementation */
I, int desiredDirection = (getDirection() + Location.RIGHT)
% Location.FULL_CIRCLE;
while (getDirection() != desiredDirection)
{
)
super.turn() ;
I super.turn();
super. turn();
Ill. setDirection(getDirection(] + Location.RIGHT);
Which of the replacements will produce the desired behavior?
(A) Lonly
(B) Honly
(©) Land Il only
(D) Land III only
(B) LM and tt
 
 
GO ON TO THE NEXT PAGE.
3940
 
23. Consider the following declarations,
Actor a = new Actor();
Bug b = new Bug();
Rock r = new Rock();
Critter ¢ = new Critter();
Consider the following lines of code.
Line: int dirl = c.getDirection();
Line2: int dir2 = a.getDirection();
Line 3: int dix3 = b.getDirection();
Line 4:  ArrayList rLoc = r.getMoveLocations(
¢.getMoveLocations();
Line 5:  ArrayList cLoc
Which of the lines of code above will cause a compile time error?
(A) Line 1 only
(B) Lines 2 and 3 only
(C) Line 4 only
(D) Line 5 only
(E) Lines 4 and 5 only
 
 
 
 
GO ON TO THE NEXT PAGConsider the following TestBug class declaration.
public class TestBug extends Bug
public void act()
t
if (canMove())
{
move () ;
if (canMove())
move();
y
else
t
setDirection(getDirection() + Location.HAL¥_CIRCLE) ;
)
)
y
The following code segment will produce @ grid that has a Rock object anda TestBug object placed as
shown.
Grid g = new PoundedGrid (5, 5);
Rock r = new Rock();
x.putSelfInGrid(g, new Location(2, 1));
Bug t = new TestBug()
t.putSelfIncrid(g, new Location(3, 2));
 
 
 
 
 
Fa
 
 
 
 
 
 
 
 
Which of the following best describes what the TestBug object t does as a result of calling t.act () ?
(A) Moves forward two locations and remains facing current direction
(B) Moves forward two locations and turns 180 degrees
(©) Moves forward one location and remains facing current direction
(D) Moves forward one location and turns 180 degrees
(B) Stays in the same location and turns 180 degrees
 
 
GOON TO THE NEXT PAGE. aABA DancingCritter isa Critter that moves in the following manner. The DancingCritter
‘makes a left turn if at least one of its neighbors is another DancingCritter. It then moves like a
Critter. Ifnone of its neighbors are DancingCritter objects, it moves likea Critter without
making a left turn. In all other respects, a DancingCritter acts like a Critter by eating neighbors that
are not rocks or critters. Consider the following implementations,
I public class DancingCritter extends Critter
{
public ArrayList getActors()
{
ArrayList actors = new ArrayList();
for (Actor a : getGrid() .getNeighbors (getLocation())}
‘
if (a instanceof DancingCritter)
actors.add(a) ;
)
return actors;
}
public void processActors(ArrayList actors)
‘ae (actors.size() > 0)
‘ setDirection(getDirection() + Location.LEFT) ;
buper. procosshetors actors)
 
Il. public class DancingCritter extends Critter
c
public void processActors(ArrayList actors)
€
boolean turning = false;
for (Actor a : actors)
t
if (a instanceof DancingCritter)
turning = true;
)
if (turning)
setDirection(getDirection() + Location.LEFT) ;
)
)
)
 
[Unauthorised copying o oun of
42 any part of is page a og
 
 
 
 
GO ON TO THE NEXT PACI. public class DancingCritter extends critter
(
public void maketfove(Location loc)
{
boolean turning = false;
for (Actor a : getGrid() .getNeighbors (getLocation()})
«
if (a instanceof DancingCritter)
turning = true;
d
if (turning)
(
setDirection(getDirection() + Location.LEFT) ;
y
super .makeMove (loc) ;
‘Thich of the proposed implementations will correctly implement the DancingCritter clas
\) Lonly
3) Ionly
2) Ml only
9) Land I only
1,1, and It
 
 
‘Garza copying arousal]
par ofthis pagel lege.
 
GO ON TO THF NFXT PAGE
aa26. Consider the following cade segment.
int k =
while (k < 10)
C
System.out.print((k % 3) +");
 
 
if ((e $3) == 0)
kek +2;
else
kee;
)
What is printed as @ result of executing the code segment?
(Ayo 21 0 2
(Bo 20 20 2
o210210
(Po 20 202 0
@®o121212
 
 
GO ON TO THE NEXT PAGConsider the following method, Method al1Even isintended to retum true if all elements inamay arr
are even numbers; otherwise, it should retum false.
public boolean allsven(int{] arr)
{
boolean isEven = /* expression */ ;
for (int k = 0; k < arr.length; k++)
t
/* loop body */
)
return isEven;
)
Which of the following replacements for /* expression */ and /* loop body */ should be used
so that method al1Bven will work as intended?
* expression */ * loop body *
A) false if ((arr(k) % 2) == 0)
isEven = true;
 
(B) false if ((arr[k] % 2) != 0)
isBven = false;
else
isEven = true;
© true if (arr(k] % 2) != 0)
 
isEven = false;
() true if ((arr{k] % 2)
isEven = false;
else
isEven = true;
 
© true if (larr{k] % 2) == 0)
isEven = false;
else
isEven = true;
 
GO ON TO THE NEXT PAGE.
4528. Consider the following code segment.
int x = /* some integer value */ ;
int y = /* some integer value */ ;
boolean result = (x < y);
result = ( (x >= y) && !result );
Which of the following best describes the conditions under which the value of result willbe true after
the code segment is executed?
(A) Only when x < y
(B) Only when x >= y
(© Only when x and y are equal
(D) The value will always be true.
(E) The value wilh never be true.
 
46
29.
Consider the following code segment.
 
for (int outer
(
for (int inner = 0; inner <= outer; inner++)
{
0; outer  db)
is equivalent to which of the following?
(A) true
(B) false
© as=b
@) at=b
(©) "a  b)
 
GO ON TO THE NEXT PAGE. a732. Consider the following code segment,
48
int a
int b
while (b != 0)
 
 
System.out.printin(a);
What is printed as a result of executing the code segment?
(ayo
8) 6
©
(D) 24
© 30
 
(Unauthorized copying rouse a]
any pat of is pagel Hegel
 
 
 
GO ON TO THE NEXT PAGE3. Consider the following method.
public int sol (int Lim)
“int s = 0;
for (int outer = 1; outer <= lim; outer++)
fl
for (int inner = outer; inner <= lim; inner++}
(
st:
}
3}
return s;
)
‘What value is returned as a result of the call sol (10) ?
(A) 20
(B) 45
© 55
() 100
(E) 385
 
 
GOON TOTHENEXTPAGE. 49.34. Consider the following incomplete method. Method £indNext. is intended to return the index of the first
occurrence of the value val beyond the position start inamay arr.
// returns index of first occurrence of val in arr
// after position star!
// xeturns arr. length if val is not found
public int findNext(int[] arr, int val, int start)
t
int pos = start + 1;
 
while ( /* condition */ }
post;
return pos;
)
For example, consider the following code segmem.
  
int(] arr = (11, 22, 100, 33, 100, 11, 44, 100);
System. out .printin(findNext (arr, 100, 2));
The execution of the code segment should result im the value 4 being printed
Which of the following expressions could be used to replace /* condition */ sothat findNext will
work as intended?
() {pes < arr. length) && (arr[pos) != val)
(B) (arr[pos] != val) && (pos < arr.length}
(© {pos < arr.length) || (arr{pos] != val)
(D) (arr[pos} == val) && (pos < arr.length)
() (pos < arr length) || (arr{pos] == val)
 
[Uneuthorzad copying rouse a]
 
 
 
50 sry par hs pape fe Megs GO ON TO THE NEXT PAG!5. Consider the following code segments.
Lo int k= 1;
while (k < 20)
if (k%3 == 1)
system.out.print( k + *
 
 
Ml, for (int k = 1; k < 20; k++)
(
if (ce $3 == 1)
System.out.print( k +" ");
M1, for (int k = 1; k < 20; k=k +3)
(
y
System.out.print( k +" ");
Which of the code segments above will produce the following output?
1 4 7 10 13 16 19
(A) Lonly
(B) Ionly
(©) Land I only
(D) Hand 111 only
(B) 1,1, and
 
GO ON TO THE NEXT PAGE.
6152
a
 
36. Consider the following two methods that appear within 3s
  
public void changeIt(int{] list, int num)
(
list
 
 
new int [5];
0;
for (int x
list [x]
0; x < list.length; x++)
 
0
 
public void start()
(
int{] nums = (1, 2, 3, 4, 5);
int value = 6;
changert (nums, value) ;
for (int k = 0; k < nums.length
System.out.print (nums[k] + "
 
ket)
 
 
System. out .print (value) ;
)
What is printed as a result of the call start () ?
(00000
00000
(1234
(12345
(E) changeTt. will throw an exception.
 
[Unauthorised copying or euse a
ary par of is pag a aga
 
 
 
gle class.
GO ON TO THE NEXT PAGE7, Consider the following declaration of the class NumSequence, which has a constructor that is intended to
initialize the instance variable seq toan ArrayList of numberOfValues random floating-point
values in the range [0.0, 1.0).
public class NumSequence
{
private ArrayList seq:
// precondition: numberOfValues > 0
// postcondition: seq has been initialized to an ArrayList of
i" length numberOfValues; each element of seq
uw contains a random Double in the range [0.0, 1.0)
public Numgequence(int numberofValues)
€
/* missing code */
)
)
Which of the following code segments could be used to replace /* missing code */ so that the
‘constructor will work as intended?
L ArrayList seq = new ArrayList (1;
for (int k = 0; k < numberOfValues; k++)
seq.add(new Double (Nath. random()));
I seq = new ArrayList();
for (int k = 0; k < numberOfValues; k++)
seq.add(new Double (Math, random())) ;
 
I, ArrayList temp = new ArrayList();
for (int k = 0; k < numberOfValues; k++)
temp.add(new Double (Math.random())) ;
seq = temp;
(A) Honly
(B) Monty
(©) Land tt
(D) Land tt
(E) Wand Ul
 
 
GO ON TO THE NEXT PAGE. 53oa |any pert otis page egal
 
38. Consider the following code segment.
double a
double b =
  
Bt
1.2;
if ((a+b) * (a -b)
{
 
(a * a) - tb * by)
system. out .printIn (‘Mathematical error!*);
}
Which of the following best describes why the phrase “Mathematical error!" would be printed?
(Remember that mathematically (a +b) *(a-b) = a?-b?.)
(A) Precedence rules make the if condition true.
(B) Associativity rules make the if condition true.
(©) Roundoff error makes the if condition tre.
(D) Overflow makes the i£ condition true
(©) A compiler bug or hardware error has occurred.
 
39. Consider the following recursive method.
public static String recur{int val)
i
String dig =
 
+ (val 83);
if (val / 3 > 0)
return dig + recur(val / 3);
return dig;
)
What is printed as a result of executing the following statement?
System.out.print1n (recur (32)};
(A) 20
(B) 102
© 210
(D) 1020
(©) 2101
 
Unaathorzed copying or rouse]
 
 
 
GO ON TO THE NEXT PAG0. Consider the following method.
public String goAgain(String str, int index)
{
if (index >= str.length())
return str;
return str + goAgain(str.substring(index), index + 1);
¥
What is printed as a result of executing the following statement?
System.out .printin(goagain(*"today", 1))+
(A) today
(B) todayto
(©) todayoday
(D) todayodayay
(E) todayodaydayayy
END OF SECTION!
IF YOU FINISH BEFORE TIME IS CALLED,
YOU MAY CHECK YOUR WORK ON THIS SECTION.
DO NOT GO ON TO SECTION Il UNTIL YOU ARE TOLD TO DO SO.
 
5556
NO TEST MATERIAL ON THIS PAGEContent of Appendixes
 
 
   
   
Appendix A... A Exam Java Quick Reference
Appendix B . Testable API
Appendix C.. . Testable Code for APCS A/AB
Appendix E. sess. Quick Reference A/AB
Appendix Goeee.e ec cececeveeeeeeceeeeueeeeeeeeeeees Index for Source Code
875
Appendix A ‘A Java Quick Reference
Appendix A — A Exam Java Quick Reference
Accessible Methods from the Java Library That May Be Included on the Exam
class java.lang.Object
* boolean equals (Object other)
© String tostring()
class java-lang. Integer
© Integer (int value)
© int intvalue()
clase java-lang.Double
* Double (double value)
* double doublevalue()
class java-lang.string
© int length()
© String substring(int from, int to) // retums the substring beginning at from
17 and ending at to-1
© string substringlint from) // rewms substring (from, Length())
© int indexof (string str) 7/- seturns the index of the first occurrence of St;
1/ returns ~1 if not found
© int compareTo(String other) 1/ returns a value <0 if this isless than other
 
J/ retums.a value =0if this isequal to other
1/ returns a value >Oi€ this is greater than other
class java.lang.Math
* static int abs(int x)
* static double abs (double x)
* static double pow(double base, double exponent)
* static double
.¢ double
  
// returns a double inthe range (0.0, 10)
class java.util .arrayList
© int size()
* boolean add(E obi) 17 appends obj toend of list; retums true
© void add(int index, © obj) 1/ inserts obj at position index (0 < index < size),
17 moving elements at position index and higher
77 to the ight (adds 110 their indices) and adjusts size
 
 
* © get (int index)
© E set(int index, £ obj) 11. replaces the element at position index with obj
17 returns the element formerly atthe specified position
© E remove(int index) // removes element from position index, moving elements
1/ at position index + 1 and higher to the left
// (subtracts | from their indices) and adjusts size
//- returns the element formerly atthe specified position
-Al-Appendix B Testable API
Appendix B — Testable API
info.gridworld.grid.Location class (implements Comparable)
public Location(int r, int c)
constructs a location with given row and column coordinates
public int getRow()
returns the row of this location
public int getCol()
returns the column of this location
public Location getAdjacentLocation(int direction)
returns the adjacent location in the direction that is closest to Airect ion
public int getDirectionToward(Location target)
returns the closest compass direction from this location toward target
public boolean equals (Object other)
retums true if other isa Location with the same row and column as this location; false otherwise
public int hashCode()
retums a hash code for this location
public int compareTo(Object other)
returns a negative integer if this location is less than other, zero ifthe two locations are equal, or a positive
integer if this location is greater than other. Locations are ordered in row-major order.
Precondition: other isa Location object.
public String toString()
retums a string with the row and column ofthis location, n the format (row, col)
‘Compass directions:
public static final int NORTH = 0;
public static final int BAST = 90;
public static final int SOUTH = 180;
public static final int WES? = 270
public static final int NORTHEAST = 45
public static final int SOUTHEAST = 135;
public static final int SOUTHWEST = 225;
public static final int NORTHWEST = 315;
 
 
‘Tum angles:
 
  
public static final int
public static final int
public static
public static
public static
public static
public static
RIGHT = 90;
int BALF_LE
int HALF_RIGHT = 45;
int FULL_CIRCLE = 36
int HALF _CIRCLE
int AHEAD = 0
 
  
    
-BI-
59Appendix B Testable API
info.gridworld.grid.Grid interface
int getNumRows ()
returns the number of rows, or-1 if this grid is unbounded
int getwuncols()
retums the number of columns, or -1 if this grid is unbounded
boolean isValid(Location loc)
retums true if Loc is validin this grid, false otherwise
Precondition: loc isnot null
 
put (Location loc, E obj)
Puts obj at location 1oc in this grid and returns the object previously at that location (or null ifthe
location was previously unoccupied).
Precondition: (1) Loc is valid in this grid 2) obj js not null
 
B remove(Location loc)
removes the object at location Loc from this grid and returns the object that was removed (or nul if the
location is unoccupied)
Precondition: Loc is valid in this grid
 
B get (Location loc)
returns the object at location loc (or null ifthe location is unoccupied)
Precondition: Loc is valid inthis grid
 
ArrayList getOccupiedLocations()
returns an array list of all occupied locations in this grid
ArrayList getValidadjacentLocations (Location loc)
returns an array list of the valid locations adjacent to Loc in this grid
Precondition: Loc is valid in this grid
ArrayList getEmptyAdjacentLocations (Location loc)
rotums an array list ofthe valid empty locations adjacent to oc in this grid
Precondition: loc is valid inthis grid
ArrayList get0ccupiedAdjacentLocations (Location loc)
retums an array list ofthe valid occupied locations adjacent to loc in this grid
Precondition: Loc is valid in this grid
 
ArrayList getNeighbors (Location loc)
returns an array list of the objects in the occupied locations adjacent to Loc in this grid
Precondition: Loc is valid in this grid
 
-B2-Appendix B Testable API
info.gridworld.actor.Actor class
public Actor ()
constructs a blue actor that is facing north
public Color getColor()
retus the color of this actor
public void setColor (Color newColor)
sels the color of this actor to newColor
public int getDirection()
returns the direction of this actor, an angle between 0 and 359 degrees
public void setDirection(int newDirection)
sets the direction of this actor to the angle between 0 and 359 degreps that is equivalent to newDirection
public GridcActor> getGrid()
returns the grid ofthis actor, or nu. if this actor isnot contained in a grid
public Location getLocation (}
returns the location of this actor, or nul. if this actor is not contained in a grid
public void putSelfinGrid(Gridcactor> gr, Location loc)
puts this actor into location loc of grid gr. Ifthere is another actor at Loc, it is removed.
Precondition: (1) This actor is not contained in a grid (2) Loc is valid in gx
public void removeSelfFromGrid()
removes this actor from its grid.
Precondition: this actor is contained in a grid
public void moveTo(Location newLocation)
moves this actor to newLocation. Ifthere is another actor at newLocat ion, itis removed.
Precondition: (1) This actor is contained in a grid (2) newLocat ion is valid in the grid ofthis actor
public void act()
reverses the direction of this actor. Override this method in subclasses of Actor to define types of actors with
different behavior
public String toString()
returns a string with the location, direction, and color of this actor
-B3- 662
Appendix B Testable API
info.gridworld.actor.Rock class (extends Actor)
public Rock()
constructs a black rock
public Rock(Color rockColor)
constructs a rock with color rockColor
public void act()
overrides the act. method in the Actor class to do nothing
info.gridworld.actor.Flower class (extends Actor)
public Flower ()
constructs a pink flower
public Flower (Color initialColer)
constructs a flower with color initiaiColor
public void act()
causes the color of this lower to darken.
-B4-\ppendix C Bug java
Appendix C — Testable Code for APCS A/AB
jug. java
ackage info.gridvorld.actor;
mport info.gridworld.grid.Grid;
mport info.gridworld.grid. Location;
mport java.awt Color;
* A. Bug is an actor that can move and tur. It drops flowers as it moves.
* The implementation of this class is testable on the AP CS A and AB Exams.
+7
UbTICr Clade BUG Tex Pens ACTOR
”
* Constructs a red bug.
y
SpubMe TRIER
¢
setColor (Color .RED) ;
)
    
GREE
 
in
* Constructs a bug of a given color.
* @param bugColor the color for this bug
a
Public Bug (CoLS¥ BugeolEH): ee AN
  
setColor (bugColor) ;
)
pe
+ Moves if it can move, turns otherwise.
”
public void act ()
 
if (canMove())
move (1;
else
curn();
+ Tums the bug 45 degrees tothe right without changing its location.
”
public void turn()
(
setDirection(getDirection|) + Location,
)
 
-Cl- PaAppendix C
Bug java
ye
* Moves the bug forward, puting flower into the location it previously occupied,
+
‘SDaeE eka aae 85 EP RT ETS A RES RO
Gridcactor> gr = getGria():
if (gr == null)
 
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr. isValid(next) }
moveTo (next);
else
removeSel {FromGrid() ;
Flower flower = new FlowerigetColor(}};
flower.putSelfInGrid(gr, loc);
 
ie
Tests whether this bug can move forward into a location that is empty or contains a flower.
* Greturn true if this bug can move.
    
 
*/
SopubLickbbreanieamtove 0 ee “
{
Grid gr = getGrid();
SE (gr == null)
return false;
Location loc =’ getLocation();
Location next = loc.getAdjacentLocat ion (getDirection()):
if (gr. isValid(next))
return false:
Actor neighbor = gr.get (next):
return (neighbor == null) || (neighbor instanceof Flower):
1. ok to move into empty location or onto flower
J not ok to move onto any other actor
 
 
-C2-\ppendix C BoxBug java
joxBug. java
mport info.gridworld.actor.Bug:
+ A BoxBug traces out a square “box” ofa given size.
+ The implementation of ths clas is testable on the AP CS A and AB Exams
+
SAS a A Ee Ae ES
private int steps;
private int sideLength;
ee
* Constructs a box bug that traces a squarc of a given side length
* Qparam length the side length
 
steps = 0;
sideLength = Length;
ye
* Moves to the next location of the square.
+
 
if (steps < sideLength && canMove())
(
move()
steps++;
)
else
(
turn ();
turn (3;
steps = 0.
?
)
-C3-
65Appendix C Critter java
Critter.java
package info.gridworld.actor;
import info.gridworld.gria.Lecation;
import java.util.arrayList;
io
* A Critter isan actor that moves through its world, processing
* other actors in some way and then moving to a new location.
* Define your own critters by extending this class and overriding any methods of this class except for act..
* When you override these methods, be sure to preserve the postconditions,
» The implementation of this class is testable on the AP CS A and AB Exams.
. ei mmo tn eee
public class Critter extends’ actor
 
* Acritter acts by getting a list of other actors, processing that lis, geting locations to move to,
* selecting one of them, and moving to the selected location,
“7
public void act()-
i
if (getcria()
return:
ArrayList actors = getactors();
processActors (actors) ;
ArrayList moveLocs = getMoveLocations();
Location loc = selectMoveLocation (moveLocs) ;
makeMove(1o¢) ;
 
 
null)
 
es
* Gets the ators for processing. Implemented to return the ators that occupy neighboring grid locations
* Override this method in subclasses to look elsewhere for actors to process.
+ Postcondition: The sate of all actor is unchanged
+ Greturn a ist of actors that this critter wishes to process,
“
public ArrayList getMoyenocations (
{
return getGrid() .getEmptyAdjacentLocations (gettocation());
)
 
   
+ Selects the location for the next move. Implemented to randomly pick one of the possible locations,
* orto retum the current location if Locs has size 0, Override this method in subclasses that
* have another mechanism for selecting the next move location,
* Postcondition: (1) The retuned location is an element of Locs, this crtter’s eurrent location, or nul.
+ (2) The state of all actors is unchanged.
+ Gparam locs the possible locations for the next move
+ @return the location that was selected for the next move.
*
public’ Location selectMoveLocation(Arraybist -
{
int n = locs.size();
if (n == 0)
return getLocation ();
int r= (int) (ath-random(} * n);
return locs.get (zr);
-C5-68
Appendix C Critter java
Moves this criter to the given location loc, or removes this critter from its grid if Loc is mulL.
An actor may be added to the old location, If there isa different actor at location Loc, that actor is
removed from the grid. Override this method in subclasses that want to earry out other actions
(for example, turning this critter or adding an occupant in its previous location).
Postcondition: (1) getLocation() == loc.
(2) The state of all actors other than those at the old and new locations is unchanged.
@param Loc the lecation to move to
1
SATEEN ca OS“ RR ete ETE
if (loc == mull)
removeSelfFromGrid() ;
else
moveTo (loc):
 
  
a
 
)
)
ChameleonCritter.java
import info.gridworld.actor Actor;
import info.gridworld actor Critter
import info.gridworld. grid. Location;
 
import java.util.ArrayList
ion
+ A ChameleonCritter takes on the color of neighboring actors as it moves through the grid
* The implementation of this class is testable on the AP CS A and AB Exams,
*
Pablie' clas’ Chameléoncritter: extendsi Crittexe igs
{
i
Randomly selects a neighbor and changes this rittr’s color tobe the same as that neighbors
+ If there are no neighbors, no action is taken,
”
3 ‘Rue vp RaiRO REN aine faSTAUTatntt
int n = actors.size();
 
   
if (n == 0)
return
int r= (int) (Math.random{) * n)
Actor other = actors. get (x);
setColor (other .getColor ()};
 
(eo
* Turns towards the new location as it moves.
i
publ ic..void: makeMowe (Locations1oc) Sake
setDirection (getLocation() .getDirectionToward(1oc) );
super .makeMove (1oc) ;
)
-C6-Appendix E GridWorld Quick Reference A/JAB
Appendix E — Quick Reference A/AB
 
Location Class (implements Comparable’
public Location(int r, int c)
public int getRow()
public int getCol ()
public Location getAdjacentLocation(int direction)
Sublic int getDirectiontoward (Location target)
dublic boolean equals(Object other)
dublic int hashcode()
sublic int compareTo(Object other)
vublic String tostring()
JORTH, EAST, SOUTH, WEST, NORTHEAST, SOUTHEAST, NORTHWEST, SOUTHWEST
JEFT, RIGHT, HALF_LEPT, HALF_RIGHT, FULLCTRCLE, HALF_CIRCLE, AHEAD
 
3rid_ Interface
nt getNumRows ()
nt_getNumCols ()
voolean isValid(Location toc}
} put (Location loc, E obj)
! remove (Location loc)
3 get (Location loc)
wraybist getOccupiedLocations()
rrayList getValidadjacentLocations (Location loc)
rraylist getEmptyAdjacentLocations (Location loc)
xrayList getOccupiedadjacentLocations (Location loc)
rrayList getNeighbors(Location 10c)
 
sctor Class
ublie Actor()
ublic Color getColor()
ublic void setColor (Color newColor)
ublic int getDirection()
ublic void setDirection(int newDirection)
vblic Grid«actor> getGrid()
ublic Location getLocation ()
ublic void putseifinGrid(Gridcactor> ex, Location loc)
ublic void removeselfFroncrid()
ublic void moveTo(Location newLocation)
ublic void act()
ublic String toString()
 
 
-El-
a70
Appendix
GridWorld Quick Reference A/AB
 
Rock Class (extends Actor)
public Rock()
public Rock (Color rockCoior)
public void act ()
 
 
Flower Class (extends Actor)
public Flower ()
public Flower (Color initialColor)
public void act ()
 
 
Bua Class (extends Actor)
public Bug()
public Bug (Color bugColor)
public void act (}
public void turn()
public void move()
public boolean canMove()
 
 
BoxBug Class (extends Bug,
public BoxBug(int 1)
public void act ()
 
 
Critter Class (extends Actor)
public void act ()
public ArrayList getActors()
public void makevfove (Location loc]
public void processActors (ArrayList actors)
public ArrayList getWoveLocations ()
public Location selectoveLocation(ArrayList locs)
 
 
 
| public void maketove (Location loc}
ChameleonCri re Cli xtends Cri
public void processActors (ArrayList actors)Appendix G Source Code Index
Appendix G — Index for Source Code
This appendix provides an index for the Java source code found in Appendix C,
Bug.java
Bug ()
Bug (Color bugColor)
act ()
turn ()
move ()
    
canMove ()
BoxBug.java
BoxBug(int length)
act ()
Critter java
act ()
getActors ()
processActors (ArrayList actors)
getMoveLocations ()
selectMoveLocation (ArrayList locs)
makeMove (Location loc)
ChameleonCritter.java
processActors (ArrayList actors)
makeMove (Location loc)
-Gl-
 
C3
c4
ca
cs
cs
cs
C6
co
C6
n72
 
The Exar
AP* Computer Science A Exam
2009
DO NOT OPEN THIS BOOKLET UNTIL YOU ARE TOLD TO DO SO.
IMPORTANT Identification Information
PLEASE PRINT WITH PEN:
      
       
     
      
   
   
   
   
   
   
   
     
  
Thou mie 1 Fate terayou staan [[] 4 Us eke oc nga
Wer Gesons lJ * tig don util ate
7 featotrtyourteeame |] rated oy seca
Pere oT Gide Eats tien sna
eo 2 natin Sivan sera tito
 
 
 
 
 
 
  
  
 
a 1 putpotes. My name and tho name of ny
Wetig beret [ School wil nt be used in ny way in
encl ea Bayar Connection wth my fre-respoase
Electronic Device aaa ‘materiale understand that am ree to
None allowed Siig ‘markNo" wath efect on my grade or
Weight T its reporting
The questions are
thee ans
‘ /
Instructions
The questions for Section I ae printed in the green insert and in this booket. You may
use the inset to organize your answers and for scratch work, but you must waite your
this pink Section Il booklet. No credit will be given for any work written in the
the orange Appendix booklet is provided for use in Section Il
 
 
‘Write your answer to each question in the space provided in the Section Il booklet. Some
questions require you to write program segments, and these must be written in Java. Show
all your work. Credit for partial solutions will be given. Write clearly and legibly. Cross
fou any errors you make. Erased or crossed-out work will not be graded.
‘Assume dss listed inthe Quick Reference found in the Appendix ar incladed in any
program that wes a program segment you write If other dasses are to be included, that
information will be specified in individual questions. Unless otherwise noted, assume that
all methods are invoked oni when their preconditions are satisfied. A Quick Reference to
required Java chess included inthe Appendix.
Manage your time carefully. Do not spend too much time on any one question. You may
proceed freely from one question to the next. You may review your responses if you finish
before the end of the exam is announcedCOMPUTER SCIENCE A
SECTION I
‘Time—1 hour and 45 minutes
Number of questions—4
Percent of total grade—S0
rections: SHOW ALL YOUR WORK. REMEMBER THAT PROGRAM SEGMENTS ARE TO BE
RITTEN IN JAVA.
tes:
‘Assume that the classes listed in the Quick Reference found in the Appendix have been imported where
appropriate.
Unless otherwise noted in the question, assume that parameters in method calls are not nu11 and that methods
are called only when their preconditions are satisfied.
 
In writing solutions for each question, you may use any of the accessible methods that are listed in classes
defined in that question. Writing significant amounts of code that can be replaced by a call to one of these
methods may not receive full credit
GO ON TO THE NEXT PAGE.
737
A statistician is studying sequences of numbers obtained by repeatedly tossing a six-sided number cube. On each
side of the number cube is a single number in the range of 1 to 6, inclusive, and no number is repeated on the
cube. The statistician is particularly interested in nuns of numbers. A run occurs when two or more consecutive
tosses of the cube produce the same value. For example, in the following sequence of cube tosses, there are runs
starting at positions 1, 6, 12, and 14.
 
 
Index 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
: a
Rest [1] [5] 4] 3][1]2]2[2]2]6][1]3][3]5]5|5]5
 
 
 
 
 
 
 
 
 
‘The number cube is represented by the following class.
public class NumberCube
t
/** @return an integer value between | and 6, inclusive
Wi
public int toss}
(/* implementation not shown */
// There may be instance variables, constructors, and methods that are not shown,
)
You will implement a method that collects the results of several tosses of a numbercube and another method
that calculates the longest run found in a sequence of tosses.
GO ON TO THE NEXT PACWrite the method getCubeTosses that takes 2 number cube and a number of tosses as parameters, The
method should return an array of the values produced by tossing the number cube the given number of times.
 
Complete method getCubeTosses below.
/** Returns an array of the values obtained by tossing a number cube numTosses times.
* @param cube a NumberCube
* @param numTosses the number of tosses tobe recorded
« Precondition: numfosses > 0
* @return anamay of nunfosses values
7
public static int[] getCubeTosses(NumberCube cube, int numTosses)
GO ON TO THE NEXT PAGE.
676
(b) Write the method getLongestRun that takes as its parameter an array of integer values representing a
series of number cube tosses. The method returns the starting index in the array of a run of maximum size. A
run is defined as the repeated occurrence of the same value in two or more consecutive positions in the
stray.
For example, the following array contains two runs of length 4, one starting at index 6 and another starting at
index 14. The method may retum either of those starting indexes.
If there are no runs of any value, the method returns. ~1.
Index 0 1 2 3 4 5 6 7 8 9 10 II 12 13 14 15 16 17
Resut [1] 5] s[4]3[1[2]2]2]2fe]ijajal{s|s sis
 
 
 
 
 
 
 
 
 
 
 
 
WRITE YOUR SOLUTION ON THE NEXT PAGE.
GO ON TO THE NEXT PAGimplete method getLongestRun below.
* Returns the starting index of a longest run of two or more consecutive repeated values,
inthe array values.
@param values an array of integer values representing a series of number cube tosses
Precondition: values. length > 0
@return the starting index of a run of maximum size;
<1 if there is no run
/
blic static int getLongestRun(int[{] values)
GO ON TO THE NEXT PAGE.
72. This question involves reasoning about the code from the GridWorld case study. A copy of the code is provided
as part of this exam.
A StockpileCritter isa Critter that uses other actors as a source of energy. Each actor represents
one unit of energy. The StockpileCritter behaves likea Critter except in the way that it interacts
with other actors. Each time the StockpileCritter acts, it gathers all neighboring actors by removing
them from the grid and keeps track of them in a stockpile. The StockpileCritter then attempts to reduce
its stockpile by one unit of energy. If the stockpile is emply, the StockpileCritter runs out of energy and
removes itself from the grid.
Consider the following scenario,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
INITIAL WORLD AFTER ONE ACT AFTER TWO ACTS
IE He ka
Stockpilecritter Gathered 3 actors, No actors gathered,
is in location 2, 2), used L energy unit, used 1 energy unit,
stockpile is empty 2 remaining in stockpile, 1 remaining in stockpile,
moved to location (3, 3) moved to location (4, 3)
AFTER THREE ACTS AFTER FOUR ACTS AFTER FIVE ACTS
Gathered | actor, No actors gathered, Stockpile empty,
used 1 energy unit, used I energy unit, removed self from grid
remaining in stockpile, O remaining in stockpile,
moved to location (3, 2) ‘moved to location (3, 3)
Write the complete StockpileCritter class, including all instance variables and required methods.
Do NOT override the act. method. Remember that your design must not violate the postconditions of the
‘methods of the Critter class and that updating an object’ instance variable changes the state of that object.
7 GO ON TO THE NEXT PACADDITIONAL WORK SPACE.
GO ON TO THE NEXT PAGE. 793. An electric car that runs on batteries must be periodically recharged for a certain number of hours. The battery
technology in the car requires thatthe charge time not be interrupted.
‘The cost for charging is based on the hour(s) during which the charging occurs. A rate table lists the 24 one-hour
periods, numbered from 0 to 23, and the corresponding hourly cost for each period. The same rate table is used
for each day. Each hourly cost is a positive integer. A sample rate table is given below.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hour Cost Hour — Cost Hour Cost
0 50 8 150 200
1 60 9 150 “17 | 200
2 160 | 10 130 18 180
3 60 | u 200 19 180
4 80 2 40 20 140
5 100 13 | 240 au 100
6 100 14 | 220 [2 80
\7 20 1s | 220 23 60.
The class BatteryCharger below uses a rate table to determine the most economic time to charge
the battery. You will write two of the methods for the BatteryCharger class.
public class BatteryCharger
/** rateTable has 24 entries representing the charging costs for hours 0 through 23. */
private int{]}-rateTable;
/** Determines the total cost to charge the battery starting at the beginning of startHour.
* @param startHour the hour at which the charge period begins
* Precondition: 0 < startHour < 23
* Gparam chargeTime the number of hours the battery needs to be charged
. Precondition: chargeTime > 0
* @return the total cost to charge the battery
”
private int: getChargingcost (ints dtareHoun eS aUaReeIED
{ /* tobe implemented in part (a) */ }
/** Determines start time to charge the battery at the lowest cost for the given charge time.
* @param chargeTime the number of hours the battery needs to be charged
Precondition: chargeTime > 0
* @return an optimal start time, with 0 < returned value < 23
“7
public int getChargeStartTime(int chargeTime)
{ /* tobe implemented in part (b) */
 
1) There may be instance variables, constructors, and methods that are not shown,
GO ON TO THE NEXT PAGE2) Writethe BatteryCharger method getChargingCost that returns the total cost to charge a
battery given the hour at which the charging process will start and the number of hours the battery needs to
be charged.
For example, using the rate table given at the beginning of the question, the following table shows the
resulting costs of several possible charges.
 
 
 
 
 
 
 
Start Hour of Hours of Charge 1 Last Hour of Total Cost
Charge Time Charge
12 i 12 0
[o 2 i 110
2 7 4 (the next day) 550
[2 30 3 (ewo days lates) 710
 
Note that a charge period consists of consecutive hours that may extend over more than one day.
Complete method getChargingCost below.
/** Determines the total cost 1o charge the battery starting at the beginning of startHour.
* @param startHour the hour at which the charge period begins
* Precondition: 0 < startHour < 23
* Gparam chargeTime the number of hours the battery needs to be charged
Precondition: chargeTime > 0
@return the total cost to charge the battery
private int getChargingCost (int startHour, int chargeTime)
GO ON TO THE NEXT PAGE. at8&
(b) Write the BatteryCharger method getChargeStartTime that retums the start time that will
allow the battery to be charged at minimal cost. If there is more than one possible start time that produces
the minimal cost, any of those start times can be returned.
For example, using the rate table given at the beginning of the question, the following table shows the
resulting minimal costs and optimal starting hour of several possible charges.
 
 
 
 
 
 
Hours of Charge | Minimum Cost | Start Hour of |Last Hour of Charge
Time Charge
1 40 2 2
0 1
2 110 or
2B O (the next day)
7 550 2 4 (the next day)
30 3,710 22 3 (two days later)
 
 
 
 
 
WRITE YOUR SOLUTION ON THE NEXT PAGE.
GO ON TO THE NEXT PAGAssume that getChargingCost works as specified, regardless of what you wrote in part (a)
 
Complete method getChargeStartTime below.
/** Determines start time to charge the battery at the lowest cost for the given charge time.
* @param chargeTime the number of hours the battery needs to be charged.
* Precondition: chargeTime > 0
* @return an optimal start time, with 0 < retumed value < 23
*
public int getChargeStartTime(int chargeTime)
GO ON TO THE NEXT PAGE. 834. A game uses square tiles that have numbers on their sides. Bach tile is labeled with a number on each ofits
four sides and may be rotated clockwise, as illustrated below.
 
INITIAL AFTER | AFTER 2 AFTER 3 (AFTER 4
ROTATION ROTATIONS ROTATIONS ROTATIONS.
4 4 7 foo3 A
4 3 7 4 3 4 4 7 4 3
1 3 4 4 7
The tiles are represented by the NumberTile class, as given below.
public class NumberTile
t
J** Rotates the tile 90 degrees clockwise
7
public void rotate()
{ /* implementation not shown */
7/** @return valueat left edge of tile
public int getheft()
( /* implementation not shown */
/** @return value at right edge of tile
+s
public int, getRight()
{ /* implementationnot shown */
/ 1 There may be instance variables, constructors, and methods that are not shown.
)
Tiles are placed on a game board so that the adjoining sides of adjacent tiles have the same number. The
following figure illustrates an arrangement of tiles and shows a new tile that is to be placed on the game board.
   
 
GAME BOARD NEW TILE
4 6 1 3 5 Gees
4 3/]3 4] la 2) j2 2) f2 9
1 3 3 5 2
1 2 4
 
a4 GO ON TO THE NEXT PAGEits original orientation, the new tile can be inserted between the tiles at positions 2 and 3 or between the tiles
positions 3 and 4. Ifthe new tile is rotated once, it can be inserted before the tile at position 0 (the first tie) or
er the tile at position 4 (the last tile). Assume that the new tile, in its original orientation, is inserted between
les at positions 2 and 3. As a result of the insertion, the tiles at positions 3 and 4 are moved one location to
2 right, and the new tile is inserted at position 3, as shown below.
 
 
GAME BOARD AFTER INSERTING TILE
2
in) 1 2
partial definition of the TileGame class is given below.
public class TileGame
(
J** represents the game board; guaranteed never to be null */
private ArrayList board;
 
public TileGame()
{ board = new Arraylist(); }
 
/** Determines where to insert tile, in its current orientation, into game board
@param tile the tile to be placed on the game board
@return the position of tile where tile is to be inserted
0 if the board is empty;
-1 if tile does not fit in front, at end, or between any existing tiles
otherwise, 0 < position retuned < board.size()
”“
private int getIndexForFit (NumberTile tile)
{/* tobe implemented in part (a) */
/** Places tile on the game board if it fits (checking all possible tile orientations if necessary)
If there are no tiles on the game board, the tie is placed at position 0.
The tile should be placed at most 1 time.
+ Precondition: board isnot null
G@param tile the tile to be placed on the game board
@return true if tile is placed successfully: false otherwise
+ Posteondition: the orientations of the other ties on the bord are not changed
Postcondition: the order of the other tiles on the board relative to each other is not changed.
 
 
 
”
public boolean insertTile(NumberTile tile)
{  /* tobe implemented in part (b) */
// There may be instance variables, constructors, and methods that are not shown,
GO ON TO THE NEXT PAGE. 55