| Learning Objective | Essential Knowledge |
|---|---|
1.1.A |
|
1.1.B |
|
1.1.C |
|
AP Computer Science A
-
1 Using Objects and Methods
1.1
Introduction to Algorithms, Programming, and Compilers
Syllabus
Source: College Board AP Course and Exam Description
An algorithm 算法 is a finite, step-by-step procedure that solves a problem. A program 程序 expresses an algorithm in a language a computer can run. Java is compiled 编译: the compiler 编译器 translates your source code into bytecode, which the Java Virtual Machine (JVM) runs. A syntax error 语法错误 (breaking the grammar) is caught by the compiler; a logic error 逻辑错误 (wrong result) is not – the program runs but misbehaves.
A compiler translates the whole program at once; an interpreter runs it line by lineVocabulary TrainEnglish Chinese Pinyin algorithm 算法 suàn fǎ program 程序 chéng xù compiled 编译 biān yì compiler 编译器 biān yì qì syntax error 语法错误 yǔ fǎ cuò wù logic error 逻辑错误 luó jí cuò wù 1.2
Variables and Data Types
Syllabus
Learning Objective Essential Knowledge 1.2.A
Identify the most appropriate data type category for a particular specification.- 1.2.A.1 A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
- 1.2.A.2 The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
- 1.2.A.3 A reference type is used to define objects that are not primitive types.
1.2.B
Develop code to declare variables to store numbers and Boolean values.- 1.2.B.1 The three primitive data types used in this course are
int,double, andboolean. Anintvalue is an integer. Adoublevalue is a real number. Abooleanvalue is eithertrueorfalse.- Exclusion statement: The other five primitive data types (
long,short,byte,float, andchar) are outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: The other five primitive data types (
- 1.2.B.2 A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.
Source: College Board AP Course and Exam Description
A variable 变量 is a named box that stores a value of a fixed type 类型. Java's main primitive types 基本类型 are
int(whole numbers),double(decimals), andboolean(true/false). Declare with the type first:
Java's basic data types, each storing a different kind of valueint score = 90; double price = 4.99; boolean passed = true;ExploreExplore how a variable holds one value at a time
A variable is a named box that stores one value of a fixed type. Step through the lines and watch each box take its value; notice that reassigning
scoreoverwrites the old number rather than making a new box.Vocabulary TrainEnglish Chinese Pinyin variable 变量 biàn liàng type 类型 lèi xíng primitive types 基本类型 jī běn lèi xíng 1.3
Expressions and Output
Syllabus
Learning Objective Essential Knowledge 1.3.A
Develop code to generate output and determine the result that would be displayed.- 1.3.A.1
System.out.printandSystem.out.printlndisplay information on the computer display.System.out.printlnmoves the cursor to a new line after the information has been displayed, whileSystem.out.printdoes not.
1.3.B
Develop code to utilize string literals and determine the result of using string literals.- 1.3.B.1 A literal is the code representation of a fixed value.
- 1.3.B.2 A string literal is a sequence of characters enclosed in double quotes.
- 1.3.B.3 Escape sequences are special sequences of characters that can be included in a string. They start with a
\and have a special meaning in Java. Escape sequences used in this course include double quote\", backslash\\, and newline\n.
1.3.C
Develop code for arithmetic expressions and determine the result of these expressions.- 1.3.C.1 Arithmetic expressions, which consist of numeric values, variables, and operators, include expressions of type
intanddouble. - 1.3.C.2 The arithmetic operators consist of addition
+, subtraction-, multiplication*, division/, and remainder%. An arithmetic operation that uses twointvalues will evaluate to anintvalue. An arithmetic operation that uses at least onedoublevalue will evaluate to adoublevalue.- Exclusion statement: Expressions that result in special double values (e.g., infinities and NaN) are outside the scope of the AP Computer Science A course and exam.
- 1.3.C.3 When dividing numeric values that are both
intvalues, the result is only the integer portion of the quotient. When dividing numeric values that use at least onedoublevalue, the result is the quotient. - 1.3.C.4 The remainder operator
%is used to compute the remainder when one numberais divided by another numberb.- Exclusion statement: The use of values less than
0foraand the use of values less than or equal to0forbis outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: The use of values less than
- 1.3.C.5 Operators can be used to construct compound expressions. At compile time, numeric values are associated with operators according to operator precedence to determine how they are grouped. Parentheses can be used to modify operator precedence. Multiplication, division, and remainder have precedence over addition and subtraction. Operators with the same precedence are evaluated from left to right.
- 1.3.C.6 An attempt to divide an integer by the integer zero will result in an
ArithmeticException.- Exclusion statement: The use of dividing by zero when one numeric value is a
doubleis outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: The use of dividing by zero when one numeric value is a
Source: College Board AP Course and Exam Description
An expression 表达式 combines values and operators to compute a result:
+ - * /and%(modulus 取模, the remainder). Integer division truncates:7 / 2is3, while7 % 2is1. Operator precedence follows math (*,/,%before+,-). Print with:System.out.print("no newline"); System.out.println("with newline");ExploreExplore the order of operations step by step
Java applies
*,/,%before+and-, working left to right. Watch each step and see why2 + 3 * 4is $14$, not $20$ — the multiplication happens first.Vocabulary TrainEnglish Chinese Pinyin expression 表达式 biǎo dá shì modulus 取模 qǔ mó 1.4
Assignment Statements and Input
Syllabus
Learning Objective Essential Knowledge 1.4.A
Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.- 1.4.A.1 Every variable must be assigned a value before it can be used in an expression. That value must be from a compatible data type. A variable is initialized the first time it is assigned a value. Reference types can be assigned a new object or
nullif there is no object. The literalnullis a special value used to indicate that a reference is not associated with any object. - 1.4.A.2 The assignment operator
=allows a program to initialize or change the value stored in a variable. The value of the expression on the right is stored in the variable on the left.- Exclusion statement: The use of assignment operators inside expressions (e.g.,
a = b = 4;ora[i += 5]) is outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: The use of assignment operators inside expressions (e.g.,
- 1.4.A.3 During execution, an expression is evaluated to produce a single value. The value of an expression has a type based on the evaluation of the expression.
1.4.B
Develop code to read input.- 1.4.B.1 Input can come in a variety of forms, such as tactile, audio, visual, or text. The
Scannerclass is one way to obtain text input from the keyboard.- Exclusion statement: Any specific form of input from the user is outside the scope of the AP Computer Science A course and exam.
Source: College Board AP Course and Exam Description
An assignment 赋值
x = expr;evaluates the right side and stores it in the left variable. Read input with aScanner:Scanner in = new Scanner(System.in); int age = in.nextInt(); String name = in.next();Vocabulary TrainEnglish Chinese Pinyin assignment 赋值 fù zhí 1.5
Casting and Range of Variables
Syllabus
Learning Objective Essential Knowledge 1.5.A
Develop code to cast primitive values to different primitive types in arithmetic expressions and determine the value that is produced as a result.- 1.5.A.1 The casting operators
(int)and(double)can be used to convert from adoublevalue to anintvalue (or vice versa). - 1.5.A.2 Casting a
doublevalue to anintvalue causes the digits to the right of the decimal point to be truncated. - 1.5.A.3 Some code causes
intvalues to be automatically cast (widened) todoublevalues. - 1.5.A.4 Values of type
doublecan be rounded to the nearest integer by(int)(x + 0.5)for non-negative numbers or(int)(x - 0.5)for negative numbers.
1.5.B
Describe conditions when an integer expression evaluates to a value out of range.- 1.5.B.1 The constant
Integer.MAX_VALUEholds the value of the largest possibleintvalue. The constantInteger.MIN_VALUEholds the value of the smallest possibleintvalue. - 1.5.B.2 Integer values in Java are represented by values of type
int, which are stored using a finite amount (4 bytes) of memory. Therefore, anintvalue must be in the range fromInteger.MIN_VALUEtoInteger.MAX_VALUEinclusive. - 1.5.B.3 If an expression would evaluate to an
intvalue outside of the allowed range, an integer overflow occurs. The result is anintvalue in the allowed range but not necessarily the value expected.
1.5.C
Describe conditions that limit accuracy of expressions.- 1.5.C.1 Computers allot a specified amount of memory to store data based on the data type. If an expression would evaluate to a
doublethat is more precise than can be stored in the allotted amount of memory, a round-off error occurs. The result will be rounded to the representable value. To avoid rounding errors that naturally occur, useintvalues.- Exclusion statement: Other special decimal data types that can be used to avoid rounding errors are outside the scope of the AP Computer Science A course and exam.
Source: College Board AP Course and Exam Description
Each type has a fixed range; an
intoverflows past about 2.1 billion. Casting 类型转换 converts between types. Widening (inttodouble) is automatic; narrowing needs an explicit cast, which truncates (does not round):double avg = (double) total / count; // force real division int whole = (int) 3.9; // 3, truncatedExam skill: watch for integer division producing a truncated result when a decimal was expected – cast one operand to
doublefirst.Worked example. Trace each expression:
7 / 2→3(bothint, so division truncates);7.0 / 2→3.5(onedoubleforces real division);7 % 2→1(the remainder);(double) 7 / 2→3.5(the cast binds tighter than/, so it is7.0 / 2);(double) (7 / 2)→3.0(the parentheses compute7 / 2 = 3inintfirst, then widen).
The last two look alike but differ – the position of the cast decides whether the truncation happens.
ExploreWhy int and double store numbers differently
An
intholds only whole numbers in a fixed range; adoublestores a mantissa and an exponent, trading exactness for a huge range. Castingdouble→intthrows away the fraction, and a value past anint's range overflows.Vocabulary TrainEnglish Chinese Pinyin Casting 类型转换 lèi xíng zhuǎn huàn 1.6
Compound Assignment Operators
Syllabus
Learning Objective Essential Knowledge 1.6.A
Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.- 1.6.A.1 Compound assignment operators
+=,-=,*=,/=, and%=can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right and then assigns the result to the variable on the left. - 1.6.A.2 The post-increment operator
++and post-decrement operator--are used to add1or subtract1from the stored value of a numeric variable. The new value is assigned to the variable.- Exclusion statement: The use of increment and decrement operators in prefix form (e.g.,
++x) is outside the scope of the AP Computer Science A course and exam. The use of increment and decrement operators inside other expressions (e.g.,arr[x++]) is outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: The use of increment and decrement operators in prefix form (e.g.,
Source: College Board AP Course and Exam Description
Shorthands combine an operation with assignment:
x += 5meansx = x + 5; likewise-=,*=,/=,%=. The increment and decrement operatorsx++andx--add or subtract one.1.7
Application Program Interface (API) and Libraries
Syllabus
Learning Objective Essential Knowledge 1.7.A
Identify the attributes and behaviors of a class found in the libraries contained in an API.- 1.7.A.1 Libraries are collections of classes. An application programming interface (API) specification informs the programmer how to use those classes. Documentation found in API specifications and libraries is essential to understanding the attributes and behaviors of a class defined by the API. A class defines a specific reference type. Classes in the APIs and libraries are grouped into packages. Existing classes and class libraries can be utilized to create objects.
- 1.7.A.2 Attributes refer to the data related to the class and are stored in variables. Behaviors refer to what instances of the class can do (or what can be done with them) and are defined by methods.
Source: College Board AP Course and Exam Description
An API (Application Programming Interface) 应用程序接口 is the published list of classes and methods you may use. A library 库 is a collection of ready-made classes (like
Math,String,Scanner). You read the API documentation to learn what a method needs (its parameters) and returns, without seeing its inner code – an example of abstraction 抽象.Vocabulary TrainEnglish Chinese Pinyin Interface 应用程序接口 yìng yòng chéng xù jiē kǒu library 库 kù abstraction 抽象 chōu xiàng 1.8
Documentation with Comments
Syllabus
Learning Objective Essential Knowledge 1.8.A
Describe the functionality and use of code through comments.- 1.8.A.1 Comments are written for both the original programmer and other programmers to understand the code and its functionality, but are ignored by the compiler and are not executed when the program is run. Three types of comments in Java include
/* */, which generates a block of comments;//, which generates a comment on one line; and/** */, which are Javadoc comments and are used to create API documentation. - 1.8.A.2 A precondition is a condition that must be true just prior to the execution of a method in order for it to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
- 1.8.A.3 A postcondition is a condition that must always be true after the execution of a method. Postconditions describe the outcome of the execution in terms of what is being returned or the current value of the attributes of an object.
Source: College Board AP Course and Exam Description
Comments 注释 are ignored by the compiler but explain code to humans:
//for a single line,/* ... */for a block, and/** ... */for a Javadoc comment that documents a method's purpose, parameters, and return value. Precise preconditions and postconditions are written here.Vocabulary TrainEnglish Chinese Pinyin Comments 注释 zhù shì 1.9
Method Signatures
Syllabus
Learning Objective Essential Knowledge 1.9.A
Identify the correct method to call based on documentation and method signatures.- 1.9.A.1 A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces. Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.
- 1.9.A.2 A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor. A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.
1.9.B
Describe how to call methods.- 1.9.B.1 A void method does not have a return value and is therefore not called as part of an expression.
- 1.9.B.2 A non-void method returns a value that is the same type as the return type in the header. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression.
- 1.9.B.3 An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.9.B.4 Methods are said to be overloaded when there are multiple methods with the same name but different signatures.
- 1.9.B.5 A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.
Source: College Board AP Course and Exam Description
A method signature 方法签名 is a method's name plus its parameter types, e.g.
nextInt()orsubstring(int, int). To call a method you must supply arguments 实参 that match the parameters in number, type, and order. The signature also states the return type – the type of value the method gives back (voidif none).Vocabulary TrainEnglish Chinese Pinyin method signature 方法签名 fāng fǎ qiān míng arguments 实参 shí cān 1.10
Calling Class Methods
Syllabus
Learning Objective Essential Knowledge 1.10.A
Develop code to call class methods and determine the result of those calls.- 1.10.A.1 Class methods are associated with the class, not instances of the class. Class methods include the keyword
staticin the header before the method name. - 1.10.A.2 Class methods are typically called using the class name along with the dot operator. When the method call occurs in the defining class, the use of the class name is optional in the call.
Source: College Board AP Course and Exam Description
A class (static) method 类方法 belongs to the class itself, so you call it on the class name:
ClassName.method(args). No object is needed.ExploreFollow a class-method call on the stack
Calling a class method like
Math.maxpushes a new frame onto the call stack; when the method returns a value, its frame pops and control goes back to the caller. Step through to watch the stack grow and shrink.Vocabulary TrainEnglish Chinese Pinyin class (static) method 类方法 lèi fāng fǎ 1.11
Math Class
Syllabus
Learning Objective Essential Knowledge 1.11.A
Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.- 1.11.A.1 The
Mathclass is part of thejava.langpackage. Classes in thejava.langpackage are available by default. - 1.11.A.2 The
Mathclass contains only class methods. The followingMathclass methods—including what they do and when they are used—are part of the Java Quick Reference:static int abs(int x)returns the absolute value of anintvalue.static double abs(double x)returns the absolute value of adoublevalue.static double pow(double base, double exponent)returns the value of the first parameter raised to the power of the second parameter.static double sqrt(double x)returns the nonnegative square root of adoublevalue.static double random()returns adoublevalue greater than or equal to0.0and less than1.0.
- 1.11.A.3 The values returned from
Math.random()can be manipulated using arithmetic and casting operators to produce a randomintordoublein a defined range based on specified criteria. Each endpoint of the range can be inclusive, meaning the value is included, or exclusive, meaning the value is not included.
Source: College Board AP Course and Exam Description
The
Mathclass provides static math methods:Math.abs(x),Math.pow(base, exp),Math.sqrt(x), andMath.random()(adoublein $[0,1)$). To get a random integer from0ton-1:(int)(Math.random() * n).1.12
Objects: Instances of Classes
Syllabus
Learning Objective Essential Knowledge 1.12.A
Explain the relationship between a class and an object.- 1.12.A.1 An object is a specific instance of a class with defined attributes. A class is the formal implementation, or blueprint, of the attributes and behaviors of an object.
- 1.12.A.2 A class hierarchy can be developed by putting common attributes and behaviors of related classes into a single class called a superclass. Classes that extend a superclass, called subclasses, can draw upon the existing attributes and behaviors of the superclass without replacing these in the code. This creates an inheritance relationship from the subclasses to the superclass.
- Exclusion statement: Designing and implementing inheritance relationships are outside the scope of the AP Computer Science A course and exam.
- 1.12.A.3 All classes in Java are subclasses of the
Objectclass.
1.12.B
Develop code to declare variables to store reference types.- 1.12.B.1 A variable of a reference type holds an object reference, which can be thought of as the memory address of that object.
Source: College Board AP Course and Exam Description
A class 类 is a blueprint; an object 对象 is a concrete instance 实例 built from it. A class bundles data (fields) with behavior (methods) – the heart of object-oriented programming 面向对象编程.
String,Scanner, andArrayListare all classes you instantiate.
A class diagram: private attributes and public methods
A class is a blueprint; each object is one instance built from itVocabulary TrainEnglish Chinese Pinyin class 类 lèi object 对象 duì xiàng instance 实例 shí lì object-oriented programming 面向对象编程 miàn xiàng duì xiàng biān chéng 1.13
Object Creation and Storage (Instantiation)
Syllabus
Learning Objective Essential Knowledge 1.13.A
Identify, using its signature, the correct constructor being called.- 1.13.A.1 A class contains constructors that are called to create objects. They have the same name as the class.
- 1.13.A.2 A constructor signature consists of the constructor's name, which is the same as the class name, and the ordered list of parameter types. The parameter list, in the header of a constructor, lists the types of the values that are passed and their variable names.
- 1.13.A.3 Constructors are said to be overloaded when there are multiple constructors with different signatures.
1.13.B
Develop code to declare variables of the correct types to hold object references.- 1.13.B.1 A variable of a reference type holds an object reference or, if there is no object,
null.
1.13.C
Develop code to create an object by calling a constructor.- 1.13.C.1 An object is typically created using the keyword
newfollowed by a call to one of the class's constructors. - 1.13.C.2 Parameters allow constructors to accept values to establish the initial values of the attributes of the object.
- 1.13.C.3 A constructor argument is a value that is passed into a constructor when the constructor is called. The arguments passed to a constructor must be compatible in order and number with the types identified in the parameter list in the constructor signature. When calling constructors, arguments are passed using call by value. Call by value initializes the parameters with copies of the arguments.
- 1.13.C.4 A constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the constructor before continuing. Once the last statement in the constructor has been executed, the flow of control is returned to the point immediately following where the constructor was called.
Source: College Board AP Course and Exam Description
Instantiation 实例化 creates an object with the
newkeyword, which calls a constructor 构造函数:Scanner in = new Scanner(System.in); String s = new String("hi"); // or just "hi"The variable holds a reference 引用 (the object's address), not the object itself. Two references can point to the same object; comparing them with
==compares addresses, not contents.
A primitive variable holds its value directly, a reference holds an arrow to the objectVocabulary TrainEnglish Chinese Pinyin Instantiation 实例化 shí lì huà constructor 构造函数 gòu zào hán shù reference 引用 yǐn yòng 1.14
Calling Instance Methods
Syllabus
Learning Objective Essential Knowledge 1.14.A
Develop code to call instance methods and determine the result of these calls.- 1.14.A.1 Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods.
- 1.14.A.2 A method call on a
nullreference will result in aNullPointerException.
Source: College Board AP Course and Exam Description
An instance method 实例方法 acts on a specific object, so you call it on the object reference:
object.method(args). Example:in.nextInt(),word.length().Vocabulary TrainEnglish Chinese Pinyin instance method 实例方法 shí lì fāng fǎ 1.15
String Manipulation
Syllabus
Learning Objective Essential Knowledge 1.15.A
Develop code to create string objects and determine the result of creating and combining strings.- 1.15.A.1 A
Stringobject represents a sequence of characters and can be created by using a string literal or by calling theStringclass constructor. - 1.15.A.2 The
Stringclass is part of thejava.langpackage. Classes in thejava.langpackage are available by default. - 1.15.A.3 A
Stringobject is immutable, meaning once aStringobject is created, its attributes cannot be changed. Methods called on aStringobject do not change the content of theStringobject. - 1.15.A.4 Two
Stringobjects can be concatenated together or combined using the+or+=operator, resulting in a newStringobject. A primitive value can be concatenated with aStringobject. This causes the implicit conversion of the primitive value to aStringobject. - 1.15.A.5 A
Stringobject can be concatenated with any object, which implicitly calls the object'stoStringmethod (a behavior that is guaranteed to exist by the inheritance relationship every class has with theObjectclass). An object'stoStringmethod returns a string value representing the object. Subclasses ofObjectoften override thetoStringmethod with class-specific implementation. Method overriding occurs when a public method in a subclass has the same method signature as a public method in the superclass, but the behavior of the method is specific to the subclass.- Exclusion statement: Overriding the
toStringmethod of a class is outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: Overriding the
1.15.B
Develop code to call methods on string objects and determine the result of calling these methods.- 1.15.B.1 A
Stringobject has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in aStringIndexOutOfBoundsException. - 1.15.B.2 The following
Stringmethods—including what they do and when they are used—are part of the Java Quick Reference:int length()returns the number of characters in aStringobject.String substring(int from, int to)returns the substring beginning at indexfromand ending at indexto - 1.String substring(int from)returnssubstring(from, length()).int indexOf(String str)returns the index of the first occurrence ofstr; returns-1if not found.boolean equals(Object other)returnstrueifthiscorresponds to the same sequence of characters asother; returnsfalseotherwise.int compareTo(String other)returns a value < 0 ifthisis less thanother; returns zero ifthisis equal toother; returns a value > 0 ifthisis greater thanother. Strings are ordered based upon the alphabet.- Exclusion statement: Using the
equalsmethod to compare oneStringobject with an object of a type other thanStringis outside the scope of the AP Computer Science A course and exam.
- 1.15.B.3 A string identical to the single element substring at position
indexcan be created by callingsubstring(index, index + 1).
Source: College Board AP Course and Exam Description
Stringobjects are immutable 不可变 – methods return a new string rather than changing the original. Key methods (all indices start at0):s.length(); // number of characters s.substring(2, 5); // chars at index 2,3,4 (5 excluded) s.indexOf("ab"); // first position, or -1 s.equals(other); // content comparison (never use == for Strings) s.compareTo(other); // <0, 0, >0 by dictionary orderExam skill:
substring(a, b)includes indexabut excludesb, and String comparison must use.equals, not==– two of the most-tested String pitfalls.Worked example. Let
String s = "COMPUTER";(indices0–7). Thens.length()is8;s.substring(0, 4)is"COMP"(indices0,1,2,3– index4excluded);s.substring(4)is"UTER"(from index4to the end);s.indexOf("PU")is3; ands.indexOf("X")is-1(not found). Counting the excluded endpoint ofsubstringis the single most common slip.
String indices start at 0ExploreExplore string indices and slicing
Every character has an index, and the numbering starts at 0. Drag the start and end to see how
substring(from, to)takes the characters fromfromup to — but not including —to.Vocabulary TrainEnglish Chinese Pinyin immutable 不可变 bù kě biàn 1.15
Exam tips
- Trace code by hand line by line, tracking each variable's value in a table — the exam rewards careful tracing over guessing.
- Know Java's primitive types and that integer division truncates ($7/2$ gives $3$); use a cast or a double for real division.
- Distinguish compile-time errors (syntax, types) from run-time errors (divide by zero, null) and logic errors (wrong output).
- Follow operator precedence and initialise every variable before you use it.
- On the free-response, write complete, compilable Java — return the right type and match the method header exactly.
-
2 Selection and Iteration
2.1
Selection and Repetition in Algorithms
Syllabus
Learning Objective Essential Knowledge 2.1.A
Represent patterns and algorithms that involve selection and repetition found in everyday life using written language or diagrams.- 2.1.A.1 The building blocks of algorithms include sequencing, selection, and repetition.
- 2.1.A.2 Algorithms can contain selection, through decision making, and repetition, via looping.
- 2.1.A.3 Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
- 2.1.A.4 Repetition is when a process repeats itself until a desired outcome is reached.
- 2.1.A.5 The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm.
Source: College Board AP Course and Exam Description
Algorithms are built from three control structures 控制结构: sequence (steps in order), selection 选择 (choosing a path), and iteration 迭代 (repeating steps). This topic covers selection and iteration – the tools that let a program make decisions and loop.
The three control structures: sequence, selection, and iterationVocabulary TrainEnglish Chinese Pinyin control structures 控制结构 kòng zhì jié gòu selection 选择 xuǎn zé iteration 迭代 dié dài 2.2
Boolean Expressions
Syllabus
Learning Objective Essential Knowledge 2.2.A
Develop code to create Boolean expressions with relational operators and determine the result of these expressions.- 2.2.A.1 Values can be compared using the relational operators
==and!=to determine whether the values are the same. With primitive types, this compares the actual primitive values. With reference types, this compares the object references. - 2.2.A.2 Numeric values can be compared using the relational operators
<,>,<=, and>=to determine the relationship between the values. - 2.2.A.3 An expression involving relational operators evaluates to a Boolean value.
Source: College Board AP Course and Exam Description
A boolean expression 布尔表达式 evaluates to
trueorfalse, using relational operators 关系运算符:==(equal),!=(not equal),<,>,<=,>=. Note==compares primitive values but object references for objects, so use.equalsforStrings.
The three families of operators: arithmetic, relational, and logicalExploreExplore the AND truth table
A Boolean expression evaluates to
trueorfalse. AND is true only when both operands are true; toggle the inputs to see all four cases.Vocabulary TrainEnglish Chinese Pinyin boolean expression 布尔表达式 bù ěr biǎo dá shì relational operators 关系运算符 guān xì yùn suàn fú 2.3
The if Statement
Syllabus
Learning Objective Essential Knowledge 2.3.A
Develop code to represent branching logical processes by using selection statements and determine the result of these processes.- 2.3.A.1 Selection statements change the sequential execution of statements.
- 2.3.A.2 An
ifstatement is a type of selection statement that affects the flow of control by executing different segments of code based on the value of a Boolean expression. - 2.3.A.3 A one-way selection (
ifstatement) is used when there is a segment of code to execute under a certain condition. In this case, the body is executed only when the Boolean expression istrue. - 2.3.A.4 A two-way selection (
if-elsestatement) is used when there are two segments of code—one to be executed when the Boolean expression istrueand another segment for when the Boolean expression isfalse. In this case, the body of theifis executed when the Boolean expression istrue, and the body of theelseis executed when the Boolean expression isfalse.
Source: College Board AP Course and Exam Description
An if statement 条件语句 runs a block only when its condition is true; an optional
elsegives an alternative:if (score >= 60) { System.out.println("Pass"); } else { System.out.println("Fail"); }ExploreSee which branch an if chooses
An if statement runs its body only when the condition is true, otherwise it skips to
else. Slide the score across the boundaries and watch the grade change.Vocabulary TrainEnglish Chinese Pinyin if statement 条件语句 tiáo jiàn yǔ jù 2.4
Nested if Statements
Syllabus
Learning Objective Essential Knowledge 2.4.A
Develop code to represent nested branching logical processes and determine the result of these processes.- 2.4.A.1 Nested
ifstatements consist ofif,if-else, orif-else-ifstatements withinif,if-else, orif-else-ifstatements. - 2.4.A.2 The Boolean expression of the inner nested
ifstatement is evaluated only if the Boolean expression of the outerifstatement evaluates totrue. - 2.4.A.3 A multiway selection (
if-else-if) is used when there are a series of expressions with different segments of code for each condition. Multiway selection is performed such that no more than one segment of code is executed based on the first expression that evaluates totrue. If no expression evaluates totrueand there is a trailingelsestatement, then the body of theelseis executed.
Source: College Board AP Course and Exam Description
Placing an
ifinside another, or chaining withelse if, tests several cases in order. Only the first matching branch runs:if (g >= 90) grade = 'A'; else if (g >= 80) grade = 'B'; else grade = 'C';2.5
Compound Boolean Expressions
Syllabus
Learning Objective Essential Knowledge 2.5.A
Develop code to represent compound Boolean expressions and determine the result of these expressions.- 2.5.A.1 Logical operators
!(not),&&(and), and||(or) are used with Boolean expressions. The expression!aevaluates totrueifaisfalseand evaluates tofalseotherwise. The expressiona && bevaluates totrueif bothaandbaretrueand evaluates tofalseotherwise. The expressiona || bevaluates totrueifaistrue,bistrue, or both, and evaluates tofalseotherwise. The order of precedence for evaluating logical operators is!(not),&&(and), then||(or). An expression involving logical operators evaluates to a Boolean value. - 2.5.A.2 Short-circuit evaluation occurs when the result of a logical operation using
&&or||can be determined by evaluating only the first Boolean expression. In this case, the second Boolean expression is not evaluated.
Source: College Board AP Course and Exam Description
Logical operators 逻辑运算符 combine conditions:
&&(and – both true),||(or – at least one true),!(not – reverse). Java uses short-circuit evaluation 短路求值:&&stops if the left side is false, and||stops if the left side is true – useful to guard against errors, e.g.if (n != 0 && total / n > 5).Vocabulary TrainEnglish Chinese Pinyin Logical operators 逻辑运算符 luó jí yùn suàn fú short-circuit evaluation 短路求值 duǎn lù qiú zhí 2.6
Comparing Boolean Expressions
Syllabus
Learning Objective Essential Knowledge 2.6.A
Compare equivalent Boolean expressions.- 2.6.A.1 Two Boolean expressions are equivalent if they evaluate to the same value in all cases. Truth tables can be used to prove Boolean expressions are equivalent.
- 2.6.A.2 De Morgan's law can be applied to Boolean expressions to create equivalent Boolean expressions. Under De Morgan's law, the Boolean expression
!(a && b)is equivalent to!a || !band the Boolean expression!(a || b)is equivalent to!a && !b.
2.6.B
Develop code to compare object references using Boolean expressions and determine the result of these expressions.- 2.6.B.1 Two different variables can hold references to the same object. Object references can be compared using
==and!=. - 2.6.B.2 An object reference can be compared with
null, using==or!=, to determine if the reference actually references an object. - 2.6.B.3 Classes often define their own
equalsmethod, which can be used to specify the criteria for equivalency for two objects of the class. The equivalency of two objects is most often determined using attributes from the two objects.- Exclusion statement: Overriding the
equalsmethod is outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: Overriding the
Source: College Board AP Course and Exam Description
De Morgan's laws 德摩根定律 rewrite negations:
!(a && b)equals!a || !b, and!(a || b)equals!a && !b. Two boolean expressions are equivalent if they give the same result for every input – a truth table proves it. Simplifying conditions this way is a common exam task.Vocabulary TrainEnglish Chinese Pinyin De Morgan's laws 德摩根定律 dé mó gēn dìng lǜ 2.7
while Loops
Syllabus
Learning Objective Essential Knowledge 2.7.A
Identify when an iterative process is required to achieve a desired result.- 2.7.A.1 Iteration is a form of repetition. Iteration statements change the flow of control by repeating a segment of code zero or more times as long as the Boolean expression controlling the loop evaluates to
true. - 2.7.A.2 An infinite loop occurs when the Boolean expression in an iterative statement always evaluates to
true. - 2.7.A.3 The loop body of an iterative statement will not execute if the Boolean expression initially evaluates to
false. - 2.7.A.4 Off by one errors occur when the iteration statement loops one time too many or one time too few.
2.7.B
Develop code to represent iterative processes usingwhileloops and determine the result of these processes.- 2.7.B.1 A
whileloop is a type of iterative statement. Inwhileloops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates totrue, the loop body is executed. This continues until the Boolean expression evaluates tofalse, whereupon the iteration terminates.
Source: College Board AP Course and Exam Description
A while loop 循环 repeats while its condition stays true, testing before each pass. You must change something inside so the loop eventually stops, or it becomes an infinite loop 无限循环:
The three loop types differ in where the condition is testedint i = 0; while (i < 5) { System.out.println(i); i++; }ExploreTrace a while loop
A while loop repeats as long as its condition stays true, updating its variables each pass. Step through to see the sum of squares build up.
Vocabulary TrainEnglish Chinese Pinyin while loop 循环 xún huán infinite loop 无限循环 wú xiàn xún huán 2.8
for Loops
Syllabus
Learning Objective Essential Knowledge 2.8.A
Develop code to represent iterative processes usingforloops and determine the result of these processes.- 2.8.A.1 A
forloop is a type of iterative statement. There are three parts in aforloop header: the initialization, the Boolean expression, and the update. - 2.8.A.2 In a
forloop, the initialization statement is only executed once before the first Boolean expression evaluation. The variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the increment statement until it isfalse. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again. - 2.8.A.3 A
forloop can be rewritten into an equivalentwhileloop (and vice versa).
Source: College Board AP Course and Exam Description
A for loop packs initialization, condition, and update into one line – best when you know the count:
for (int i = 0; i < n; i++) { // runs n times, i = 0..n-1 }A
forand an equivalentwhiledo the same work; be able to convert between them.ExploreTrace a for loop
A for loop runs a fixed number of times, its counter stepping through a range. Watch the counter and running total advance one pass at a time.
2.9
Building Complete Selection and Iteration Algorithms
Syllabus
Learning Objective Essential Knowledge 2.9.A
Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.- 2.9.A.1 There are standard algorithms to:
- identify if an integer is or is not evenly divisible by another integer
- identify the individual digits in an integer
- determine the frequency with which a specific criterion is met
- determine a minimum or maximum value
- compute a sum or average
Source: College Board AP Course and Exam Description
Combine loops and conditions to solve real problems – count, sum, find a maximum, or test a property:
int max = arr[0]; for (int k = 1; k < arr.length; k++) { if (arr[k] > max) max = arr[k]; }Standard patterns like a running total, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.
Vocabulary TrainEnglish Chinese Pinyin flag 标志 biāo zhì 2.10
String Algorithms
Syllabus
Learning Objective Essential Knowledge 2.10.A
Develop code for standard and original algorithms that involve strings and determine the result of these algorithms.- 2.10.A.1 There are standard string algorithms to:
- find if one or more substrings have a particular property
- determine the number of substrings that meet specific criteria
- create a new string with the characters reversed
Source: College Board AP Course and Exam Description
Loop through a string by index to process each character:
for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // count vowels, reverse, check for a substring, ... }Typical tasks: count occurrences, build a reversed or filtered copy, or test whether one string contains another.
2.11
Nested Iteration
Syllabus
Learning Objective Essential Knowledge 2.11.A
Develop code to represent nested iterative processes and determine the result of these processes.- 2.11.A.1 Nested iteration statements are iteration statements that appear in the body of another iteration statement. When a loop is nested inside another loop, the inner loop must complete all its iterations before the outer loop can continue to its next iteration.
Source: College Board AP Course and Exam Description
A nested loop 嵌套循环 puts one loop inside another; the inner loop completes fully for each pass of the outer. If the outer runs $n$ times and the inner $m$ times, the body runs $n\times m$ times – the basis for processing grids and comparing all pairs.
Vocabulary TrainEnglish Chinese Pinyin nested loop 嵌套循环 qiàn tào xún huán 2.12
Informal Run-Time Analysis
Syllabus
Learning Objective Essential Knowledge 2.12.A
Calculate statement execution counts and informal run-time comparison of iterative statements.- 2.12.A.1 A statement execution count indicates the number of times a statement is executed by the program. Statement execution counts are often calculated informally through tracing and analysis of the iterative statements.
Source: College Board AP Course and Exam Description
Run-time analysis 运行时间分析 counts how many basic steps an algorithm takes as the input size $n$ grows. Count the executions of the innermost statement: a single loop over $n$ items is linear ($n$ steps); two nested loops over $n$ are quadratic ($n^2$). This informal counting lets you compare two algorithms' efficiency.
How the running time grows with the number of elements nExam skill: for a nested loop, be able to state how many times the inner statement runs in terms of the loop bounds – a frequent multiple-choice question.
Worked example. How many stars does this print?
for (int i = 0; i < 4; i++) for (int j = 0; j < i; j++) System.out.print("*");The inner loop runs
itimes for each outeri:0 + 1 + 2 + 3 = 6stars. When the inner bound is the outer variable, the total is the triangular sum $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ – here $\dfrac{4\times3}{2}=6$ – not the full $n^2=16$ of a rectangular nested loop.ExploreCompare how algorithms scale
Run-time describes how the number of steps grows with the input size $n$. Increase $n$ and watch a linear $O(n)$ pull far ahead of a quadratic $O(n^2)$.
Vocabulary TrainEnglish Chinese Pinyin Run-time analysis 运行时间分析 yùn xíng shí jiān fēn xī 2.12
Exam tips
- Get boundary conditions right: use
<vs<=deliberately, and watch the first and last iteration of every loop (off-by-one is the classic bug). - Build compound conditions with
&&,||,!and remember short-circuit evaluation (put the null check first). - Trace nested loops by counting how many times the inner body runs in total.
- Choose the right structure —
if/else iffor ranges, a loop for repetition — and avoid an infinite loop by updating the loop variable. - Apply De Morgan's laws when you simplify or negate a boolean condition.
-
3 Class Creation
3.1
Abstraction and Program Design
Syllabus
Learning Objective Essential Knowledge 3.1.A
Represent the design of a program by using natural language or creating diagrams that indicate the classes in the program and the data and procedural abstractions found in each class by including all attributes and behaviors.- 3.1.A.1 Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
- 3.1.A.2 Data abstraction provides a separation between the abstract properties of a data type and the concrete details of its representation. Data abstraction manages complexity by giving data a name without referencing the specific details of the representation. Data can take the form of a single variable or a collection of data, such as in a class or a set of data.
- 3.1.A.3 An attribute is a type of data abstraction that is defined in a class outside any method or constructor. An instance variable is an attribute whose value is unique to each instance of the class. A class variable is an attribute shared by all instances of the class.
- 3.1.A.4 Procedural abstraction provides a name for a process and allows a method to be used only knowing what it does, not how it does it. Through method decomposition, a programmer breaks down larger behaviors of the class into smaller behaviors by creating methods to represent each individual smaller behavior. A procedural abstraction may extract shared features to generalize functionality instead of duplicating code. This allows for code reuse, which helps manage complexity.
- 3.1.A.5 Using parameters allows procedures to be generalized, enabling the procedures to be reused with a range of input values or arguments.
- 3.1.A.6 Using procedural abstraction in a program allows programmers to change the internals of a method (to make it faster, more efficient, use less storage, etc.) without needing to notify method users of the change as long as the method signature and what the method does is preserved.
- 3.1.A.7 Prior to implementing a class, it is helpful to take time to design each class including its attributes and behaviors. This design can be represented using natural language or diagrams.
Source: College Board AP Course and Exam Description
Abstraction 抽象 means hiding detail behind a simple interface – you use a
Stringwithout knowing how it stores characters. Good design breaks a problem into classes, each responsible for one idea. This topic is about writing your own classes.
Decomposing a program into modules and sub-modulesVocabulary TrainEnglish Chinese Pinyin Abstraction 抽象 chōu xiàng 3.2
The Impact of Program Design
Syllabus
Learning Objective Essential Knowledge 3.2.A
Explain the social and ethical implications of computing systems.- 3.2.A.1 System reliability refers to the program being able to perform its tasks as expected under stated conditions without failure. Programmers should make an effort to maximize system reliability by testing the program with a variety of conditions.
- 3.2.A.2 The creation of programs has impacts on society, the economy, and culture. These impacts can be both beneficial and harmful. Programs meant to fill a need or solve a problem can have unintended harmful effects beyond their intended use.
- 3.2.A.3 Legal issues and intellectual property concerns arise when creating programs. Programmers often reuse code written by others and published as open source and free to use. Incorporation of code that is not published as open source requires the programmer to obtain permission and often purchase the code before integrating it into their program.
Source: College Board AP Course and Exam Description
Design choices affect whether code is correct, readable, and reusable. Encapsulation 封装 – keeping data private and exposing it only through methods – protects an object's state from misuse and lets you change the inside without breaking users of the class. Thoughtful naming, single-purpose methods, and testing reduce bugs.
Vocabulary TrainEnglish Chinese Pinyin Encapsulation 封装 fēng zhuāng 3.3
The Anatomy of a Class
Syllabus
Learning Objective Essential Knowledge 3.3.A
Develop code to designate access and visibility constraints to classes, data, constructors, and methods.- 3.3.A.1 Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords
publicandprivateaffect the access of classes, data, constructors, and methods. The keywordprivaterestricts access to the declaring class, while the keywordpublicallows access from classes outside the declaring class. - 3.3.A.2 In this course, classes are always designated
publicand are declared with the keywordclass. - 3.3.A.3 In this course, constructors are always designated
public. - 3.3.A.4 Instance variables belong to the object, and each object has its own copy of the variable.
- 3.3.A.5 Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as
privateunless the class specification states otherwise. - 3.3.A.6 Access to behaviors can be internal or external to the class. Methods designated as
publiccan be accessed internally or externally to a class, whereas methods designated asprivatecan only be accessed internally to the class.
Source: College Board AP Course and Exam Description
A class has three parts: instance variables 实例变量 (fields – the object's data), constructors (build objects), and methods (behavior). Fields are usually
private; methods are usuallypublic:
A class diagram: private attributes and public methodspublic class Student { private String name; // instance variable private int score; public Student(String n, int s) { // constructor name = n; score = s; } public int getScore() { return score; } // accessor }ExploreSee an object's fields as boxes
A class groups related data (its fields) and methods. Each object gets its own set of field boxes; assigning to one changes that object only.
Vocabulary TrainEnglish Chinese Pinyin instance variables 实例变量 shí lì biàn liàng 3.4
Constructors
Syllabus
Learning Objective Essential Knowledge 3.4.A
Develop code to declare instance variables for the attributes to be initialized in the body of the constructors of a class.- 3.4.A.1 An object's state refers to its attributes and their values at a given time and is defined by instance variables belonging to the object. This defines a has-a relationship between the object and its instance variables.
- 3.4.A.2 A constructor is used to set the initial state of an object, which should include initial values for all instance variables. When a constructor is called, memory is allocated for the object and the associated object reference is returned. Constructor parameters, if specified, provide data to initialize instance variables.
- 3.4.A.3 When a mutable object is a constructor parameter, the instance variable should be initialized with a copy of the referenced object. In this way, the instance variable does not hold a reference to the original object, and methods are prevented from modifying the state of the original object.
- 3.4.A.4 When no constructor is written, Java provides a no-parameter constructor, and the instance variables are set to default values according to the data type of the attribute. This constructor is called the default constructor.
- 3.4.A.5 The default value for an attribute of type
intis0. The default value of an attribute of typedoubleis0.0. The default value of an attribute of typebooleanisfalse. The default value of a reference type isnull.
Source: College Board AP Course and Exam Description
A constructor 构造函数 has the same name as the class and no return type. It runs when you write
new, and its job is to initialize the fields. A class can have several constructors with different parameter lists (overloading 重载); a no-argument constructor sets defaults.Vocabulary TrainEnglish Chinese Pinyin constructor 构造函数 gòu zào hán shù overloading 重载 zhòng zài 3.5
Methods: How to Write Them
Syllabus
Learning Objective Essential Knowledge 3.5.A
Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.- 3.5.A.1 A
voidmethod does not return a value. Its header contains the keywordvoidbefore the method name. - 3.5.A.2 A non-void method returns a single value. Its header includes the return type in place of the keyword
void. - 3.5.A.3 In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value.
- 3.5.A.4 The
returnkeyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed. Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor. - 3.5.A.5 An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method.
- 3.5.A.6 A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method.
- 3.5.A.7 Methods with parameters receive values through those parameters and use those values in accomplishing the method's task.
- 3.5.A.8 When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.
Source: College Board AP Course and Exam Description
A method has a signature, a return type, and a body. An accessor (getter) 访问器 returns information without changing the object; a mutator (setter) 修改器 changes a field. A method returning a value must have a
returnof the right type on every path; avoidmethod returns nothing.public void setScore(int s) { score = s; } // mutator public String toString() { return name + ": " + score; }ExploreFollow a method call and its return
Calling a method pushes a frame with its parameters; when it hits
return, the frame pops and the value goes back to the caller.Vocabulary TrainEnglish Chinese Pinyin accessor (getter) 访问器 fǎng wèn qì mutator (setter) 修改器 xiū gǎi qì 3.6
Passing and Returning References of an Object
Syllabus
Learning Objective Essential Knowledge 3.6.A
Develop code to define behaviors of an object through methods written in a class using object references and determine the result of calling these methods.- 3.6.A.1 When an argument is an object reference, the parameter is initialized with a copy of that reference; it does not create a new independent copy of the object. If the parameter refers to a mutable object, the method or constructor can use this reference to alter the state of the object. It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
- 3.6.A.2 When the return expression evaluates to an object reference, the reference is returned, not a reference to a new copy of the object.
- 3.6.A.3 Methods cannot access the private data and methods of a parameter that holds a reference to an object unless the parameter is the same type as the method's enclosing class.
Source: College Board AP Course and Exam Description
When you pass an object to a method, Java copies the reference, so the method acts on the same object – changes to its fields are visible to the caller. (Primitives are copied by value, so changes to them are not.) A method can also return a reference to an object. Because a
Stringis immutable, passing one is safe; passing a mutable object lets a method change it.
Pass by value gives a copy; pass by reference lets the method change the originalExam skill: know that mutating an object's fields inside a method affects the original, but reassigning the parameter (
param = new...) does not affect the caller.Worked example. Suppose
sis aStudentwith score50, and we calltweak(s):public static void tweak(Student a) { a.setScore(100); // (1) mutates the shared object a = new Student("Z", 0); // (2) repoints the local copy only a.setScore(5); // (3) changes only the new local object }Line (1) changes the object
spoints to, so the caller now sees100. Line (2) makes the method's own copy of the reference point at a fresh object – the caller'ssis untouched – and line (3) affects only that new object. After the call,s.getScore()is100: the mutation stuck, the reassignment did not.3.7
Class Variables and Class Methods
Syllabus
Learning Objective Essential Knowledge 3.7.A
Develop code to define behaviors of a class through class methods.- 3.7.A.1 Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
- 3.7.A.2 Class methods can access or change the values of class variables and can call other class methods.
3.7.B
Develop code to declare the class variables that belong to the class.- 3.7.B.1 Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the
statickeyword before the variable type. - 3.7.B.2 Class variables that are designated
publicare accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class. - 3.7.B.3 When a variable is declared
final, its value cannot be modified.
Source: College Board AP Course and Exam Description
A static (class) variable 类变量, marked
static, is shared by all objects of the class – one copy total (e.g. a counter of how many objects exist). A static method belongs to the class and cannot use instance fields directly. Access them by class name:Student.getCount().Vocabulary TrainEnglish Chinese Pinyin static (class) variable 类变量 lèi biàn liàng 3.8
Scope and Access
Syllabus
Learning Objective Essential Knowledge 3.8.A
Explain where variables can be used in the code.- 3.8.A.1 Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Since constructors and methods are blocks of code, parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be
publicorprivate. - 3.8.A.2 When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.
Source: College Board AP Course and Exam Description
Scope 作用域 is where a name is visible. A local variable declared in a method exists only inside it; a parameter exists only in its method; an instance variable is visible throughout the object. Access modifiers control visibility across classes:
private(this class only) versuspublic(anywhere). Local variables shadow fields of the same name – a source of bugs.
A global variable is visible everywhere; a local variable only inside its blockVocabulary TrainEnglish Chinese Pinyin Scope 作用域 zuò yòng yù 3.9
The this Keyword
Syllabus
Learning Objective Essential Knowledge 3.9.A
Develop code for expressions that are self-referencing and determine the result of these expressions.- 3.9.A.1 Within an instance method or a constructor, the keyword
thisacts as a special variable that holds a reference to the current object—the object whose method or constructor is being called. - 3.9.A.2 The keyword
thiscan be used to pass the current object as an argument in a method call. - 3.9.A.3 Class methods do not have a
thisreference.
Source: College Board AP Course and Exam Description
thisis a reference to the current object. Use it to tell a field apart from a parameter with the same name, or to call another method of the same object:public Student(String name, int score) { this.name = name; // this.name is the field; name is the parameter this.score = score; }Exam skill: when a constructor or setter's parameter has the same name as a field, you must write
this.field = param– withoutthis, the assignment does nothing useful.3.9
Exam tips
- Design with methods and classes: encapsulate data as
privatefields and expose behaviour through public methods. - Know the difference between an object and its class, and that objects are passed by reference (a method can change the object's state).
- Traverse arrays and
ArrayLists safely — size islengthvs.size(), and removing during a loop shifts indices. - Write and trace a recursive method: find the base case first, then check the recursive call moves toward it.
- Use inheritance and polymorphism (override,
super) so the right method runs at run time.
-
4 Data Collections
4.1
The Ethics of Collecting Data
Syllabus
Learning Objective Essential Knowledge 4.1.A
Explain the risks to privacy from collecting and storing personal data on computer systems.- 4.1.A.1 When using a computer, personal privacy is at risk. When developing new programs, programmers should attempt to safeguard the personal privacy of the user.
4.1.B
Explain the importance of recognizing data quality and potential issues when using a data set.- 4.1.B.1 Algorithmic bias describes systemic and repeated errors in a program that create unfair outcomes for a specific group of users.
- 4.1.B.2 Programmers should be aware of the data set collection method and the potential for bias when using this method before using the data to extrapolate new information or drawing conclusions.
- 4.1.B.3 Some data sets are incomplete or contain inaccurate data. Using such data in the development or use of a program can cause the program to work incorrectly or inefficiently.
4.1.C
Identify an appropriate data set to use in order to solve a problem or answer a specific question.- 4.1.C.1 Contents of a data set might be related to a specific question or topic and might not be appropriate to give correct answers or extrapolate information for a different question or topic.
Source: College Board AP Course and Exam Description
Programs that gather data raise questions of privacy 隐私 and consent 同意. Collect only what is needed, protect it, and be honest about its use. Data can carry bias 偏见 if it does not represent everyone fairly, leading to unfair results – a responsibility that comes with storing information.
Vocabulary TrainEnglish Chinese Pinyin privacy 隐私 yǐn sī consent 同意 tóng yì bias 偏见 piān jiàn 4.2
Why We Need Data Structures
Syllabus
Learning Objective Essential Knowledge 4.2.A
Represent patterns and algorithms that involve data sets found in everyday life using written language or diagrams.- 4.2.A.1 A data set is a collection of specific pieces of information or data.
- 4.2.A.2 Data sets can be manipulated and analyzed to solve a problem or answer a question. When analyzing data sets, values within the set are accessed and utilized one at a time and then processed according to the desired outcome.
- 4.2.A.3 Data can be represented in a diagram by using a chart or table. This visual can be used to plan the algorithm that will be used to manipulate the data.
Source: College Board AP Course and Exam Description
A single variable holds one value; real problems need to store many related values – a class roster, pixels, sensor readings. A data structure 数据结构 organizes a collection so we can store, find, and process items efficiently. The AP course uses three: the array, the ArrayList, and the 2D array.
Vocabulary TrainEnglish Chinese Pinyin data structure 数据结构 shù jù jié gòu 4.3
Making and Reading an Array
Syllabus
Learning Objective Essential Knowledge 4.3.A
Develop code used to represent collections of related data using one-dimensional (1D) array objects.- 4.3.A.1 An array stores multiple values of the same type. The values can be either primitive values or object references.
- 4.3.A.2 The length of an array is established at the time of creation and cannot be changed. The length of an array can be accessed through the
lengthattribute. - 4.3.A.3 When an array is created using the keyword
new, all of its elements are initialized to the default values for the element data type. The default value forintis0, fordoubleis0.0, forbooleanisfalse, and for a reference type isnull. - 4.3.A.4 Initializer lists can be used to create and initialize arrays.
- 4.3.A.5 Square brackets
[ ]are used to access and modify an element in a 1D array using an index. - 4.3.A.6 The valid index values for an array are
0through one less than the length of the array, inclusive. Using an index value outside of this range will result in anArrayIndexOutOfBoundsException.
Source: College Board AP Course and Exam Description
An array 数组 is a fixed-size, ordered collection of same-type values. Indices run from
0tolength - 1:
A one-dimensional array (a list) with its indices and boundsint[] nums = new int[5]; // five zeros int[] vals = {3, 1, 4, 1, 5}; // initialized int first = vals[0]; // 3 int n = vals.length; // 5 (a field, not a method)Accessing an index outside
0..length-1throws anArrayIndexOutOfBoundsException.Vocabulary TrainEnglish Chinese Pinyin array 数组 shù zǔ 4.4
Visiting Every Element of an Array
Syllabus
Learning Objective Essential Knowledge 4.4.A
Develop code used to traverse the elements in a 1D array and determine the result of these traversals.- 4.4.A.1 Traversing an array is when repetition statements are used to access all or an ordered sequence of elements in an array.
- 4.4.A.2 Traversing an array with an indexed
forloop orwhileloop requires elements to be accessed using their indices. - 4.4.A.3 An enhanced
forloop header includes a variable, referred to as the enhancedforloop variable. For each iteration of the enhancedforloop, the enhancedforloop variable is assigned a copy of an element without using its index. - 4.4.A.4 Assigning a new value to the enhanced
forloop variable does not change the value stored in the array. - 4.4.A.5 When an array stores object references, the attributes can be modified by calling methods on the enhanced
forloop variable. This does not change the object references stored in the array. - 4.4.A.6 Code written using an enhanced
forloop to traverse elements in an array can be rewritten using an indexedforloop or awhileloop.
Source: College Board AP Course and Exam Description
Traverse 遍历 an array with a
forloop (gives the index) or an enhanced for / for-each loop (gives each value, read-only):for (int i = 0; i < a.length; i++) { a[i] *= 2; } // can modify for (int v : a) { System.out.println(v); } // read each valueVocabulary TrainEnglish Chinese Pinyin Traverse 遍历 biàn lì 4.5
Standard Array Algorithms
Syllabus
Learning Objective Essential Knowledge 4.5.A
Develop code for standard and original algorithms for a particular context or specification that involves arrays and determine the result of these algorithms.- 4.5.A.1 There are standard algorithms that utilize array traversals to:
- determine a minimum or maximum value
- compute a sum or average
- determine if at least one element has a particular property
- determine if all elements have a particular property
- determine the number of elements having a particular property
- access all consecutive pairs of elements
- determine the presence or absence of duplicate elements
- shift or rotate elements left or right
- reverse the order of the elements
Source: College Board AP Course and Exam Description
Master these patterns: compute a sum or average, find the max/min, count items meeting a condition, check for a duplicate, and reverse or shift elements. Each is a traversal with a running result:
int sum = 0; for (int v : a) sum += v; double avg = (double) sum / a.length;4.6
Reading Data from a Text File
Syllabus
Learning Objective Essential Knowledge 4.6.A
Develop code to read data from a text file.- 4.6.A.1 A file is storage for data that persists when the program is not running. The data in a file can be retrieved during program execution.
- 4.6.A.2 A file can be connected to the program using the
FileandScannerclasses. - 4.6.A.3 A file can be opened by creating a
Fileobject, using the name of the file as the argument of the constructor.File(String str)is theFileconstructor that accepts aStringfile name to open for reading, wherestris the pathname for the file.
- 4.6.A.4 When using the
Fileclass, it is required to indicate what to do if the file with the provided name cannot be opened. One way to accomplish this is to addthrows IOExceptionto the header of the method that uses the file. If the file name is invalid, the program will terminate. - 4.6.A.5 The
FileandIOExceptionclasses are part of thejava.iopackage. Animportstatement must be used to make these classes available for use in the program. - 4.6.A.6 The following
Scannermethods and constructor—including what they do and when they are used—are part of the Java Quick Reference:Scanner(File f)is theScannerconstructor that accepts aFilefor reading.int nextInt()returns the nextintread from the file or input source if available. If the nextintdoes not exist or is out of range, it will result in anInputMismatchException.double nextDouble()returns the nextdoubleread from the file or input source. If the nextdoubledoes not exist, it will result in anInputMismatchException.boolean nextBoolean()returns the nextbooleanread from the file or input source. If the nextbooleandoes not exist, it will result in anInputMismatchException.String nextLine()returns the next line of text as aStringread from the file or input source; can return the empty string if called immediately after anotherScannermethod that is reading from the file or input source.String next()returns the nextStringread from the file or input source.boolean hasNext()returnstrueif there is a next item to read in the file or input source; returnsfalseotherwise.void close()closes this scanner.- Exclusion statement: Accepting input from the keyboard is outside the scope of the AP Computer Science A course and exam.
- 4.6.A.7 Using
nextLineand the otherScannermethods together on the same input source sometimes requires code to adjust for the methods' different ways of handling whitespace.- Exclusion statement: Writing or analyzing code that uses both
nextLineand otherScannermethods on the same input source is outside the scope of the AP Computer Science A course and exam.
- Exclusion statement: Writing or analyzing code that uses both
- 4.6.A.8 The following additional
Stringmethod—including what it does and when it is used—is part of the Java Quick Reference:String[] split(String del)returns aStringarray where each element is a substring ofthis String, which has been split around matches of the given expressiondel.- Exclusion statement: The parameter
deluses a format called a regular expression. Writing or analyzing code that uses any of the special properties of regular expressions (e.g.,\\*,\\.) is outside the scope of the AP Computer Science A course and exam.
- 4.6.A.9 A
whileloop can be used to detect if the file still contains elements to read by using thehasNextmethod as the condition of the loop. - 4.6.A.10 A file should be closed when the program is finished using it. The
closemethod fromScanneris called to close the file.
Source: College Board AP Course and Exam Description
A
Scannercan read a file line by line, usinghasNext...to test before reading:Scanner f = new Scanner(new File("data.txt")); while (f.hasNextLine()) { String line = f.nextLine(); }4.7
Wrapping a Number in an Object
Syllabus
Learning Objective Essential Knowledge 4.7.A
Develop code to useIntegerandDoubleobjects from their primitive counterparts and determine the result of using these objects.- 4.7.A.1 The
Integerclass andDoubleclass are part of thejava.langpackage. AnIntegerobject is immutable, meaning once anIntegerobject is created, its attributes cannot be changed. ADoubleobject is immutable, meaning once aDoubleobject is created, its attributes cannot be changed. - 4.7.A.2 Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an
intto anIntegerand adoubleto aDouble. The Java compiler applies autoboxing when a primitive value is:- passed as a parameter to a method that expects an object of the corresponding wrapper class
- assigned to a variable of the corresponding wrapper class
- 4.7.A.3 Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an
Integerto anintand aDoubleto adouble. The Java compiler applies unboxing when a wrapper class object is:- passed as a parameter to a method that expects a value of the corresponding primitive type
- assigned to a variable of the corresponding primitive type
- 4.7.A.4 The following class
Integermethod—including what it does and when it is used—is part of the Java Quick Reference:static int parseInt(String s)returns theStringargument as anint.
- 4.7.A.5 The following class
Doublemethod—including what it does and when it is used—is part of the Java Quick Reference:static double parseDouble(String s)returns theStringargument as adouble.
Source: College Board AP Course and Exam Description
An
ArrayListstores objects, not primitives, so a primitive is wrapped in an object:Integerwrapsint,Doublewrapsdouble. Java does this with autoboxing 自动装箱 (inttoInteger) and unboxing (back again) automatically, so you can writelist.add(5)andint x = list.get(0).Vocabulary TrainEnglish Chinese Pinyin autoboxing 自动装箱 zì dòng zhuāng xiāng 4.8
The ArrayList Toolbox
Syllabus
Learning Objective Essential Knowledge 4.8.A
Develop code for collections of related objects usingArrayListobjects and determine the result of calling methods on these objects.- 4.8.A.1 An
ArrayListobject is mutable in size and contains object references. - 4.8.A.2 The
ArrayListconstructorArrayList()constructs an empty list. - 4.8.A.3 Java allows the generic type
ArrayList<E>, where the type parameterEspecifies the type of the elements. WhenArrayList<E>is specified, the types of the reference parameters and return type when using theArrayListmethods are typeE.ArrayList<E>is preferred overArrayList. For example,ArrayList<String> names = new ArrayList<String>();allows the compiler to find errors that would otherwise be found at run-time. - 4.8.A.4 The
ArrayListclass is part of thejava.utilpackage. Animportstatement must be used to make this class available for use in the program. - 4.8.A.5 The following
ArrayListmethods—including what they do and when they are used—are part of the Java Quick Reference:int size()returns the number of elements in the list.boolean add(E obj)appendsobjto end of list; returnstrue.void add(int index, E obj)insertsobjat positionindex(0 <= index <= size), moving elements at positionindexand higher to the right (adds 1 to their indices) and adds 1 to size.E get(int index)returns the element at positionindexin the list.E set(int index, E obj)replaces the element at positionindexwithobj; returns the element formerly at positionindex.E remove(int index)removes element from positionindex, moving elements at positionindex + 1and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at positionindex.
- 4.8.A.6 The indices for an
ArrayListstart at0and end at the number of elements- 1.
Source: College Board AP Course and Exam Description
An ArrayList 动态数组 grows and shrinks as you add or remove items. Declare it with the element type in
<>:ArrayList<String> names = new ArrayList<String>(); names.add("Amy"); // append names.add(0, "Bob"); // insert at index names.get(0); // read names.set(1, "Cara"); // replace names.remove(0); // delete, shifts the rest left names.size(); // count (a method, unlike array.length)Vocabulary TrainEnglish Chinese Pinyin ArrayList 动态数组 dòng tài shù zǔ 4.9
Visiting Every Element of an ArrayList
Syllabus
Learning Objective Essential Knowledge 4.9.A
Develop code used to traverse the elements of anArrayListand determine the results of these traversals.- 4.9.A.1 Traversing an
ArrayListis when iteration or recursive statements are used to access all or an ordered sequence of the elements in anArrayList. - 4.9.A.2 Deleting elements during a traversal of an
ArrayListrequires the use of special techniques to avoid skipping elements. - 4.9.A.3 Attempting to access an index value outside of its range will result in an
IndexOutOfBoundsException. - 4.9.A.4 Changing the size of an
ArrayListwhile traversing it using an enhancedforloop can result in aConcurrentModificationException. Therefore, when using an enhancedforloop to traverse anArrayList, you should not add or remove elements.
Source: College Board AP Course and Exam Description
Traverse with an index loop or a for-each loop, just like arrays (use
size()andget(i)):for (int i = 0; i < list.size(); i++) { ... list.get(i) ... } for (String s : list) { ... }Exam skill: when removing items in an index loop, either loop backwards or do not increment
iafter a removal – otherwise removing shifts elements left and you skip one.4.10
Standard ArrayList Algorithms
Syllabus
Learning Objective Essential Knowledge 4.10.A
Develop code for standard and original algorithms for a particular context or specification that involveArrayListobjects and determine the result of these algorithms.- 4.10.A.1 There are standard
ArrayListalgorithms that utilize traversals to:- determine a minimum or maximum value
- compute a sum or average
- determine if at least one element has a particular property
- determine if all elements have a particular property
- determine the number of elements having a particular property
- access all consecutive pairs of elements
- determine the presence or absence of duplicate elements
- shift or rotate elements left or right
- reverse the order of the elements
- insert elements
- delete elements
- 4.10.A.2 Some algorithms require multiple
String, array, orArrayListobjects to be traversed simultaneously.
Source: College Board AP Course and Exam Description
The same algorithms as arrays – max/min, count, sum – plus insertion and deletion that arrays cannot do easily. A common task is to remove all elements matching a condition, handling the index-shift carefully.
4.11
Grids: Two-Dimensional Arrays
Syllabus
Learning Objective Essential Knowledge 4.11.A
Develop code used to represent collections of related data using two-dimensional (2D) array objects.- 4.11.A.1 A 2D array is stored as an array of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed. 2D arrays can store either primitive data or object reference data.
- Exclusion statement: Nonrectangular 2D array objects are outside the scope of the AP Computer Science A course and exam.
- 4.11.A.2 When a 2D array is created using the keyword
new, all of its elements are initialized to the default values for the element data type. The default value forintis0, fordoubleis0.0, forbooleanisfalse, and for a reference type isnull. - 4.11.A.3 The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example,
int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };. - 4.11.A.4 The square brackets
[row][col]are used to access and modify an element in a 2D array. For the purposes of the exam, when accessing the element atarr[first][second], the first index is used for rows, the second index is used for columns. - 4.11.A.5 A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index.
- 4.11.A.6 The number of rows contained in a 2D array can be accessed through the
lengthattribute. The valid row index values for a 2D array are0through one less than the number of rows or the length of the array, inclusive. The number of columns contained in a 2D array can be accessed through thelengthattribute of one of the rows. The valid column index values for a 2D array are0through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array namedvalues, the number of rows isvalues.lengthand the number of columns isvalues[0].length. Using an index value outside of these ranges will result in anArrayIndexOutOfBoundsException.
Source: College Board AP Course and Exam Description
A 2D array 二维数组 is a grid (rows and columns) – an array of arrays:
A two-dimensional array (a table) with row and column indicesint[][] grid = new int[3][4]; // 3 rows, 4 columns grid[r][c] = 7; // row r, column c int rows = grid.length; // 3 int cols = grid[0].length; // 4ExploreIndex a 2D array by row and column
A 2D array is a grid addressed by
[row][col]. Move the indices and watch which cell they select — row first, then column, both counting from 0.Vocabulary TrainEnglish Chinese Pinyin 2D array 二维数组 èr wéi shù zǔ 4.12
Walking Through a Grid
Syllabus
Learning Objective Essential Knowledge 4.12.A
Develop code used to traverse the elements in a 2D array and determine the result of these traversals.- 4.12.A.1 Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using
forloops and enhancedforloops is similar to 1D array objects. Nested iteration statements can be written to traverse the 2D array in row-major order, column-major order, or a uniquely defined order. Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, whereas column-major order traversal occurs down each column. - 4.12.A.2 The outer loop of a nested enhanced
forloop used to traverse a 2D array traverses the rows. Therefore, the enhancedforloop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhancedforloop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhancedforloop variable does not change the value stored in the array.
Source: College Board AP Course and Exam Description
Visit every cell with nested loops – the outer over rows, the inner over columns (row-major order 行主序):
for (int r = 0; r < grid.length; r++) for (int c = 0; c < grid[0].length; c++) System.out.print(grid[r][c]);Vocabulary TrainEnglish Chinese Pinyin row-major order 行主序 xíng zhǔ xù 4.13
Standard 2D Array Algorithms
Syllabus
Learning Objective Essential Knowledge 4.13.A
Develop code for standard and original algorithms for a particular context or specification that involves 2D arrays and determine the result of these algorithms.- 4.13.A.1 There are standard algorithms that utilize 2D array traversals to:
- determine a minimum or maximum value of all the elements or for a designated row, column, or other subsection
- compute a sum or average of all the elements or for a designated row, column, or other subsection
- determine if at least one element has a particular property in the entire 2D array or for a designated row, column, or other subsection
- determine if all elements of the 2D array or a designated row, column, or other subsection have a particular property
- determine the number of elements in the 2D array or in a designated row, column, or other subsection having a particular property
- access all consecutive pairs of elements
- determine the presence or absence of duplicate elements in the 2D array or in a designated row, column, or other subsection
- shift or rotate elements in a row left or right or in a column up or down
- reverse the order of the elements in a row or column
Source: College Board AP Course and Exam Description
Typical grid tasks: sum a row or column, find the max in the grid, count matching cells, or sum a diagonal (where
r == c). Each is a nested traversal with a running result.4.14
Finding a Value: Linear and Binary Search
Syllabus
Learning Objective Essential Knowledge 4.14.A
Develop code used for linear search algorithms to search for specific information in a collection and determine the results of executing a search.- 4.14.A.1 Linear search algorithms are standard algorithms that check each element in order until the desired value is found or all elements in the array or
ArrayListhave been checked. Linear search algorithms can begin the search process from either end of the array orArrayList. - 4.14.A.2 When applying linear search algorithms to 2D arrays, each row must be accessed then linear search applied to each row of the 2D array.
Source: College Board AP Course and Exam Description
- Linear search 线性搜索 checks each element in turn – works on any list, taking up to $n$ steps.
- Binary search 二分搜索 works only on a sorted list: check the middle, then discard the half that cannot contain the target, repeating. It takes about $\log_2 n$ steps – far faster on large data.
Binary search halves the range at each step
Linear search checks every element in turn until the target is foundint lo = 0, hi = a.length - 1; while (lo <= hi) { int mid = (lo + hi) / 2; if (a[mid] == target) return mid; else if (a[mid] < target) lo = mid + 1; else hi = mid - 1; }Exam skill: binary search requires sorted data; know how many comparisons it makes and how
lo,hi,midupdate.Worked example. Search for
target = 40in the sorted array{3, 9, 14, 23, 31, 42, 55}(indices0–6). Startlo=0, hi=6:mid = (0+6)/2 = 3,a[3]=23 < 40, solo = 4;mid = (4+6)/2 = 5,a[5]=42 > 40, sohi = 4;mid = (4+4)/2 = 4,a[4]=31 < 40, solo = 5;- now
lo (5) > hi (4), so the loop ends –40is not present.
Each step halved the range, so even this miss took only three comparisons.
ExploreCompare linear and binary search
Linear search checks every element in turn; binary search halves a sorted list each step. Watch binary search reach the target in far fewer comparisons.
Vocabulary TrainEnglish Chinese Pinyin Linear search 线性搜索 xiàn xìng sōu suǒ Binary search 二分搜索 èr fēn sōu suǒ 4.15
Putting Data in Order: Selection and Insertion Sort
Syllabus
Learning Objective Essential Knowledge 4.15.A
Determine the result of executing each step of sorting algorithms to sort the elements of a collection.- 4.15.A.1 Selection sort and insertion sort are iterative sorting algorithms that can be used to sort elements in an array or
ArrayList. - 4.15.A.2 Selection sort repeatedly selects the smallest (or largest) element from the unsorted portion of the list and swaps it into its correct (and final) position in the sorted portion of the list.
- 4.15.A.3 Insertion sort inserts an element from the unsorted portion of a list into its correct (but not necessarily final) position in the sorted portion of the list by shifting elements of the sorted portion to make room for the new element.
Source: College Board AP Course and Exam Description
- Selection sort 选择排序 repeatedly finds the smallest remaining element and swaps it into place.
- Insertion sort 插入排序 grows a sorted front, inserting each new element where it belongs.
An insertion sort, shifting each key into place pass by passBoth are simple and take about $n^2$ steps on average – fine for small arrays. Be able to trace the array after each pass.
ExploreWatch a sorting algorithm order a list
A sort rearranges elements into order. Step through selection/insertion sort to see the sorted region grow one element at a time.
Vocabulary TrainEnglish Chinese Pinyin Selection sort 选择排序 xuǎn zé pái xù Insertion sort 插入排序 chā rù pái xù 4.16
Methods That Call Themselves: Recursion
Syllabus
Learning Objective Essential Knowledge 4.16.A
Determine the result of calling recursive methods.- 4.16.A.1 A recursive method is a method that calls itself. Recursive methods contain at least one base case, which halts the recursion, and at least one recursive call. Recursion is another form of repetition.
- 4.16.A.2 Each recursive call has its own set of local variables, including the parameters. Parameter values capture the progress of a recursive process, much like loop control variable values capture the progress of a loop.
- 4.16.A.3 Any recursive solution can be replicated through the use of an iterative approach and vice versa.
- Exclusion statement: Writing recursive code is outside the scope of the AP Computer Science A course and exam.
Source: College Board AP Course and Exam Description
Recursion 递归 is a method that calls itself on a smaller input. It needs a base case 基本情况 that stops the calls, and a recursive case that moves toward the base:
public static int factorial(int n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // recursive case }Without a reachable base case, recursion never stops (a stack overflow).
ExploreUnfold a recursive call
A recursive method calls itself on a smaller input until it hits a base case, then the results fold back up. Step through to watch the calls stack and unwind.
Vocabulary TrainEnglish Chinese Pinyin Recursion 递归 dì guī base case 基本情况 jī běn qíng kuàng 4.17
Recursive Search and Merge Sort
Syllabus
Learning Objective Essential Knowledge 4.17.A
Determine the result of executing recursive algorithms that use strings or collections.- 4.17.A.1 Recursion can be used to traverse
Stringobjects, arrays, andArrayListobjects.
4.17.B
Determine the result of each iteration of a binary search algorithm used to search for information in a collection.- 4.17.B.1 Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or
ArrayListand eliminates half of the array orArrayListin each recursive call until the desired value is found or all elements have been eliminated. - 4.17.B.2 Binary search is typically more efficient than linear search.
- Exclusion statement: Search algorithms other than linear and binary search are outside the scope of the AP Computer Science A course and exam.
- 4.17.B.3 The binary search algorithm can be written either iteratively or recursively.
4.17.C
Determine the result of each iteration of the merge sort algorithm when used to sort a collection.- 4.17.C.1 Merge sort is a recursive sorting algorithm that can be used to sort elements in an array or
ArrayList.- Exclusion statement: Sorting algorithms other than selection, insertion, and merge sort are outside the scope of the AP Computer Science A course and exam.
- 4.17.C.2 Merge sort repeatedly divides an array into smaller subarrays until each subarray is one element and then recursively merges the sorted subarrays back together in sorted order to form the final sorted array.
Source: College Board AP Course and Exam Description
Recursion powers efficient algorithms. Binary search can be written recursively (search the correct half). Merge sort 归并排序 splits the array in half, sorts each half recursively, then merges the two sorted halves – taking about $n\log_2 n$ steps, much faster than selection or insertion sort on large data.
Merge sort splits the array to single elements, then merges sorted halves back upWorked example. Trace
factorial(4). Each call defers to a smaller one:factorial(4)=4 * factorial(3)=4 * 3 * factorial(2)=4 * 3 * 2 * factorial(1).factorial(1)hits the base case and returns1, so the calls unwind inward:2 * 1 = 2, then3 * 2 = 6, then4 * 6 = 24. Writing each call above its returned value is the reliable way to trace recursion.Exam skill: trace a recursive method by writing out each call and its return value, and know that merge sort's efficiency ($n\log n$) beats the $n^2$ simple sorts.
Vocabulary TrainEnglish Chinese Pinyin Merge sort 归并排序 guī bìng pái xù 4.17
Exam tips
- Weigh both benefits and harms of collecting data — this unit is tested through short written justification, not code.
- Protect personally identifiable information (PII) and explain privacy and security risks in context.
- Name real harms: data breaches, surveillance, and algorithmic bias from unrepresentative data.
- Respect intellectual property and licensing when you reuse code or data.
- Give a specific, reasoned answer — a vague "it could be bad" earns no marks.