AP Computer Science A · 鼎睿学苑

Unit 1: Using Objects
and Methods

单元 1:使用对象
与方法

Foundation of Java programming, variables, data types, expressions, the Math and String classes, and creating & using objects.

Java 编程基础:变量、数据类型、表达式、Math 类与 String 类,以及创建和使用对象。

15–25% of AP Exam 占 AP 考试 15–25% ~32–34 Class Periods 约 32–34 课时 15 Topics 15 个小节

Introduction to Algorithms, Programming, and Compilers

算法、编程与编译器入门

Algorithm A step-by-step process for completing a task or solving a problem. Can be represented with written language or diagrams.
算法(algorithm 完成某项任务或解决某个问题的一步一步的过程。可以用文字或图表来表示。

Sequencing means steps execute one at a time, in order. This is the most basic control structure in any program.

顺序执行是指各个步骤按顺序逐条执行。这是任何程序中最基本的控制结构。

The Build Process

构建流程

Write source code → Compile (javac) → Run (java) → Output

An IDE (Integrated Development Environment) bundles editing, compiling, and running into one tool. A compiler checks for errors before the program runs; errors must be fixed first.

编写源代码 → 编译(javac)→ 运行(java)→ 输出

IDE(集成开发环境)将编辑、编译和运行整合到同一个工具中。 编译器(compiler在程序运行之前会检查错误;必须先修复错误才能运行。

Three Types of Errors

三种错误类型

Error TypeWhen DetectedExample
Syntax Error Compile-time Missing semicolon, misspelled keyword
Logic Error Testing / runtime Using + instead of -; program runs but gives wrong answer
Run-time Error During execution Dividing by zero → ArithmeticException
错误类型检测时机示例
语法错误(syntax error 编译时(compile-time 缺少分号、关键字拼写错误
逻辑错误(logic error 测试 / 运行时(runtime - 写成 +;程序能运行但结果是错的
运行时错误(run-time error 执行期间 除以零 → ArithmeticException
Exception A specific kind of run-time error that interrupts normal program flow. Not caught by the compiler.
异常(exception 一种特定的运行时错误,会中断程序的正常流程。编译器无法捕获它。

Variables and Data Types

变量与数据类型

A data type is a set of values plus operations on those values. Java data types fall into two categories: primitive and reference.

数据类型是一组值以及作用于这些值的运算的集合。Java 的数据类型分为两大类:基本类型(primitive type引用类型(reference type

The Three Primitive Types (AP CSA)

三种基本类型(AP CSA)

TypeWhat It StoresExample
intIntegers (whole numbers)int age = 17;
doubleReal numbers (decimals)double gpa = 3.85;
booleantrue or falseboolean passed = true;
类型存储内容示例
int整数(整型数)int age = 17;
double实数(带小数)double gpa = 3.85;
booleantruefalseboolean passed = true;
Reference Types Used for objects (non-primitive). A reference variable stores a reference (memory address) to the object, not the object itself.
引用类型 用于对象(非基本类型)。引用变量存储的是指向对象的引用(内存地址),而不是对象本身。

A variable is a named storage location. It has a name, a type, and a value that can change while the program runs.

变量是一个有名字的存储位置。它有一个名字、一个类型,以及一个在程序运行过程中可以改变的值。

int score = 95;         // primitive, holds the value directly// 基本类型,直接保存值
String name = "Alice";  // reference, holds address of String object// 引用类型,保存指向 String 对象的地址
Quick Check: Which data type would you use to store whether a light switch is on or off?即时小测:要存储电灯开关是开还是关,应该使用哪种数据类型?
int
boolean
double
String
Correct! A light switch is either on (true) or off (false), a perfect fit for boolean.正确!电灯开关只有开(true)或关(false)两种状态,正好用 boolean
Not quite. Since a light switch only has two states (on/off), boolean is the best choice.不太对。由于电灯开关只有两种状态(开/关),boolean 是最合适的选择。

Expressions and Output

表达式与输出

Printing to the Console

打印到控制台

System.out.println("Hello!");  // prints + newline// 打印并换行
System.out.print("Hi ");       // prints, cursor stays// 打印,光标停在原行
System.out.print("there");     // continues on same line// 在同一行继续输出
// Output: Hi there// 输出:Hi there

Literals & Escape Sequences

字面量与转义序列(escape sequence

A literal is a fixed value in code. A string literal is text in double quotes: "Hello".

字面量(literal是代码中的固定值。字符串字面量是写在双引号里的文本:"Hello"

EscapeMeaningExample Output
\"Double quote"She said \"hi\"" → She said "hi"
\\Backslash"C:\\Users" → C:\Users
\nNewline"Line1\nLine2" → two lines
转义序列含义输出示例
\"双引号"She said \"hi\"" → She said "hi"
\\反斜杠"C:\\Users" → C:\Users
\n换行"Line1\nLine2" → 分成两行

Arithmetic Operators

算术运算符(operator

OperatorOperationExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division7 / 32 (int!)
%Remainder7 % 31
运算符运算示例结果
+加法7 + 310
-减法7 - 34
*乘法7 * 321
/除法7 / 32(整型!)
%取余7 % 31
Integer Division Trap 7 / 23 (not 3.5!). Both operands are int, so the result is int, the decimal is dropped. Use at least one double to get 3.5: 7.0 / 2.
整数除法陷阱 7 / 23(不是 3.5!)。两个操作数都是 int,所以结果也是 int,小数部分会被丢掉。要得到 3.5,至少要有一个 double7.0 / 2
Operator Precedence * / % happen before + - (left to right). Parentheses override precedence.
运算符优先级(precedence * / % 先于 + -(从左到右)。括号可以覆盖默认优先级。
ArithmeticException Dividing an int by 0 throws this exception at run-time.
ArithmeticException(算术异常)int 除以 0 会在运行时抛出该异常(exception)。
What is the value of 13 / 5 + 13 % 5?13 / 5 + 13 % 5 的值是多少?
5
4
5
2.6
Correct! 13 / 5 = 2 (integer division), 13 % 5 = 3, so 2 + 3 = 5.正确!13 / 5 = 2(整数除法),13 % 5 = 3,所以 2 + 3 = 5
13 / 5 = 2 (integer division), 13 % 5 = 3, so the answer is 2 + 3 = 5.13 / 5 = 2(整数除法),13 % 5 = 3,所以答案是 2 + 3 = 5
Worked Example: Mixed-type expression例题:混合类型表达式
double avg = 5 / 2 * 2.0;
// Step 1: 5 / 2 evaluates to 2 (both ints, integer division)// 第 1 步:5 / 2 = 2(两边都是 int,整数除法)
// Step 2: 2 * 2.0 evaluates to 4.0 (int gets promoted to double)// 第 2 步:2 * 2.0 = 4.0(int 被提升为 double)
// avg = 4.0, not 5.0// avg = 4.0,而不是 5.0

What tripped people up: Java evaluates left to right at equal precedence. The integer division finishes before the double ever shows up to promote anything. If you want the real average, move the 2.0 earlier (or write one of the literals as 5.0).

容易被坑的地方:当优先级相同时,Java 从左到右求值。整数除法在 double 出现之前就已经完成,根本来不及把任何东西提升为 double。如果想要真正的平均值,把 2.0 往前移(或者把其中一个字面量写成 5.0)。

AP Trap: The result type comes from the operands, not from the variable The result type of a / b depends on the types of a and b, not on what you store the result in. double d = 7 / 2; gives d = 3.0, because 7 / 2 evaluates to the int 3 first, and then that 3 gets widened to 3.0. The destination type can't reach back into the expression to fix it.
AP 陷阱:结果类型由操作数决定,而不是由变量决定 a / b 的结果类型取决于 ab 的类型,而不是你把结果存到哪里。double d = 7 / 2; 得到的是 d = 3.0,因为 7 / 2 先算成 int 3,然后这个 3 才被扩展成 3.0。赋值的目标类型并不会回头去修正表达式本身。

Assignment Statements and Input

赋值语句与输入

The assignment operator = stores the value on the right into the variable on the left. The expression on the right is evaluated first.

赋值(assignment)运算符 = 把右侧的值存入左侧的变量。右侧的表达式会先被求值。

int x = 5;
x = x + 3;  // x is now 8, right side evaluates first// x 现在是 8,右边先求值
Initialization A variable must be assigned a value before you use it. The first assignment is called initialization. Reference types can be assigned null (no object).
初始化(initialization 在使用变量之前,必须先给它赋值。第一次赋值称为初始化。 引用类型可以被赋值为 null(表示没有对象)。

Reading Input

读取输入

import java.util.Scanner;

Scanner input = new Scanner(System.in);
System.out.print("Enter age: ");
int age = input.nextInt();

Casting and Range of Variables

类型转换(casting)与变量取值范围

Casting

类型转换

Explicit casting converts one primitive type to another.

显式类型转换可以把一种基本类型(primitive type)转换成另一种。

double d = 9.7;
int n = (int) d;       // n = 9, truncates (does NOT round)// n = 9,向零截断(不是四舍五入)
double e = (double) 5; // e = 5.0// e = 5.0
Widening (Automatic) Java automatically promotes intdouble when needed (e.g., assigning an int to a double variable).
自动扩展(隐式扩宽) Java 会在需要的时候自动把 int 提升为 double(例如,把一个 int 赋值给一个 double 变量时)。
Rounding Trick (int)(x + 0.5) for non-negative numbers rounds to the nearest integer. For negatives: (int)(x - 0.5).
四舍五入技巧 对非负数,(int)(x + 0.5) 可以四舍五入到最接近的整数。对负数则用 (int)(x - 0.5)

Integer Range & Overflow

整数取值范围与溢出

int uses 4 bytes: range is Integer.MIN_VALUE (−2,147,483,648) to Integer.MAX_VALUE (2,147,483,647). Going beyond → integer overflow: result wraps around unpredictably.

int 占 4 字节:取值范围是 Integer.MIN_VALUE(−2,147,483,648)到 Integer.MAX_VALUE(2,147,483,647)。超出该范围会发生整数溢出(integer overflow:结果会以不可预测的方式回卷。

Round-off Errors double has limited precision. Expressions may produce slightly inaccurate results (e.g., 0.1 + 0.2 ≠ exactly 0.3). Use int when exact values are needed.
舍入误差 double 的精度是有限的。表达式可能产生稍有偏差的结果(例如 0.1 + 0.2 并不严格等于 0.3)。当需要精确值时,请使用 int
Worked Example: Casts truncate toward zero例题:类型转换向零截断(truncation
int a = (int) 9.7;          // 9   (drops the .7)// 9   (丢弃 .7)
int b = (int) -9.7;         // -9  (NOT -10; truncates toward zero)// -9  (不是 -10;向零截断)
double c = (int) 3.9 + 0.5;   // 3.5  (cast hits 3.9 only, then 3 + 0.5)// 3.5  (转换只作用于 3.9,然后 3 + 0.5)
int d = (int) (3.9 + 0.5);    // 4    (parentheses make the cast hit the whole sum)// 4    (括号让转换作用于整个和)

Two things to watch: the cast applies to whatever sits to its right (in line 3, just 3.9), not to the whole expression after it. And for negative doubles, the cast drops the fractional part toward zero, not toward minus infinity, so (int)(-3.9) is -3, not -4.

两点要小心:类型转换只作用于紧跟在它右边的那一项(第 3 行只作用于 3.9),而不是后面整段表达式。对负的 double 而言,转换会把小数部分向零截断,而不是向负无穷取整,所以 (int)(-3.9)-3,而不是 -4

AP Trap: Implicit widening in arithmetic Any expression that mixes an int with a double evaluates as a double. 3 + 1.0 is 4.0, not 4. To assign the result to an int variable, you need an explicit cast, and the cast will truncate the fractional part.
AP 陷阱:算术运算中的隐式扩宽 任何把 intdouble 混在一起的表达式都会按 double 计算。3 + 1.04.0,而不是 4。要把结果赋值给一个 int 变量,必须使用显式类型转换,而且转换会把小数部分截断。

Compound Assignment Operators

复合赋值运算符(operator

OperatorEquivalent ToExample
x += 5x = x + 5
x -= 3x = x - 3
x *= 2x = x * 2
x /= 4x = x / 4
x %= 3x = x % 3
x++x = x + 1Post-increment
x--x = x - 1Post-decrement
运算符等价于说明
x += 5x = x + 5
x -= 3x = x - 3
x *= 2x = x * 2
x /= 4x = x / 4
x %= 3x = x % 3
x++x = x + 1后置自增
x--x = x - 1后置自减
int score = 10;
score += 5;   // 15// 15
score *= 2;   // 30// 30
score--;       // 29// 29

Application Program Interface (API) and Libraries

应用程序接口(API)与库

Libraries are collections of pre-written classes. An API (Application Programming Interface) is documentation that tells you how to use those classes.

是一组已经写好的类的集合。API(应用程序接口)是一份文档,告诉你如何使用这些类。

Attributes vs Behaviors Attributes = data stored in variables. Behaviors = what objects can do, defined by methods.
属性 vs 行为 属性=存放在变量里的数据。行为=对象能做的事情,由方法定义。

Classes in APIs are grouped into packages. You use existing classes to create objects and call their methods.

API 中的类按来组织。你使用已有的类来创建对象,并调用它们的方法。


Documentation with Comments

使用注释做文档

// Single-line comment// 单行注释

/* Multi-line
   block comment *//* 多行
   块注释 */

/** Javadoc comment, used to
  * generate API documentation *//** Javadoc 注释,用于
  * 生成 API 文档 */
Precondition A condition that must be true before a method executes for it to work correctly. The method is not required to check it.
前置条件(Precondition) 在方法执行之前必须为真的条件,方法才能正确工作。方法本身并不要求去检查它。
Postcondition A condition guaranteed to be true after a method finishes. Describes what was returned or how the object changed.
后置条件(Postcondition) 方法执行完成之后保证为真的条件。它描述返回了什么,或者对象发生了怎样的变化。

Method Signatures

方法签名

A method is a named block of code that runs only when called. Procedural abstraction: you can use a method knowing what it does without knowing how.

方法(method是一段有名字的代码块,只有在被调用时才会执行。过程抽象:你只需要知道一个方法做什么就能使用它,而不必知道它怎么做

Method Signature The method name + ordered list of parameter types. Example: substring(int, int)
方法签名 方法名 + 有序的形参类型列表。例如:substring(int, int)

Parameters vs Arguments

形参(parameter) vs 实参(argument

Parameter: variable declared in the method header. Argument: the actual value passed in when calling the method. Java uses call by value, parameters get copies of the arguments.

形参:方法头中声明的变量。实参:调用方法时实际传入的值。Java 采用按值调用,形参拿到的是实参的副本

Void vs Non-Void Methods

void 方法 vs 非 void 方法

voidNon-void
Returns a value?NoYes
Used in expressions?No, standalone callYes, store/use the return value
void非 void
是否返回值?
能用在表达式中吗?不能,只作为独立调用能,可保存或使用返回值
Overloaded Methods Multiple methods with the same name but different signatures (different parameter lists). Java picks the right one based on the arguments.
重载方法(overloading 多个方法同名签名不同(形参列表不同)。Java 会根据实参选出正确的那一个。

When a method is called, execution jumps into that method. After the method finishes (or hits a return), control returns to the calling point.

方法被调用时,执行会跳转到该方法中。方法执行完毕(或遇到 return)后,控制权再回到调用点。


Calling Class Methods

调用类(class)方法

Class methods (also called static methods) belong to the class itself, not to any particular object. They have static in the header.

类方法(也称为静态方法)属于类本身,而不属于某个具体的对象。它们的方法头中带有 static

// Called using ClassName.methodName()// 通过 ClassName.methodName() 调用
int absVal = Math.abs(-42);  // 42// 42

If you call a static method from within the same class, the class name is optional.

如果在同一个类内部调用静态方法,类名可以省略。


Math Class

Math 类

Part of java.lang (automatically available). Contains only static methods, no objects needed.

属于 java.lang(自动可用)。只包含静态方法,不需要创建对象就能使用。

Quick Reference, Math Methods
快速参考:Math 类方法
MethodReturns
Math.abs(int x)Absolute value (int)
Math.abs(double x)Absolute value (double)
Math.pow(double b, double e)b raised to power e
Math.sqrt(double x)Square root of x
Math.random()Random double in [0.0, 1.0)
方法返回值
Math.abs(int x)绝对值(int)
Math.abs(double x)绝对值(double)
Math.pow(double b, double e)b 的 e 次幂
Math.sqrt(double x)x 的平方根
Math.random()[0.0, 1.0) 之间的随机 double

Generating Random Integers

生成随机整数

// Random int from min to max (inclusive)// 从 min 到 max(含端点)的随机整数
int roll = (int) (Math.random() * 6) + 1;  // 1–6// 1–6

// General formula: (int)(Math.random() * range) + min// 通用公式:(int)(Math.random() * range) + min
// where range = max - min + 1// 其中 range = max - min + 1
Which expression produces a random integer from 5 to 10 inclusive?下列哪个表达式生成 5 到 10(含端点)之间的随机整数?
(int)(Math.random() * 5) + 5
(int)(Math.random() * 6) + 5
(int)(Math.random() * 10) + 5
(int)(Math.random() * 6) + 4
Correct! Range = 10 − 5 + 1 = 6. So: (int)(Math.random() * 6) + 5 → values 5, 6, 7, 8, 9, 10.正确!范围 = 10 − 5 + 1 = 6。所以 (int)(Math.random() * 6) + 5 → 取值 5、6、7、8、9、10。
Range = max − min + 1 = 6. The formula is (int)(Math.random() * 6) + 5.范围 = max − min + 1 = 6。公式是 (int)(Math.random() * 6) + 5
Worked Example: Deriving the random-int formula例题:推导随机整数公式

Goal: pick a random integer from min to max inclusive.

目标:从 minmax(含端点)取一个随机整数。

Step 1. Math.random() returns a double in [0.0, 1.0).

第 1 步。Math.random() 返回一个位于 [0.0, 1.0)double

Step 2. Multiplying by n stretches the range to [0.0, n).

第 2 步。乘以 n 后,范围被拉伸到 [0.0, n)

Step 3. Casting to int truncates the fractional part, leaving an int in {0, 1, ..., n-1}, which is exactly n possible values.

第 3 步。强制转换为 int 会截断小数部分,得到 {0, 1, ..., n-1} 中的整数,正好是 n 个可能的取值。

Step 4. Adding min shifts the set to {min, min+1, ..., min+n-1}. To reach max, you need min + n - 1 = max, so n = max - min + 1.

第 4 步。再加上 min,集合就移动到 {min, min+1, ..., min+n-1}。要能取到 max,需要 min + n - 1 = max,所以 n = max - min + 1

// Random integer in [min, max] inclusive:// [min, max] 闭区间内的随机整数:
int r = (int)(Math.random() * (max - min + 1)) + min;
AP Trap: Off-by-one on the multiplier Two common wrong answers on AP MCQs: using (max - min) instead of (max - min + 1) (loses the max value, since multiplication stops just below the multiplier), or putting the cast in the wrong place. (int) Math.random() * 6 casts Math.random() first, which is always 0 as an int, so the whole thing is 0. The cast has to surround the multiplication: (int)(Math.random() * 6).
AP 陷阱:乘数上的差一错误 AP 选择题里常见的两种错答:一是用 (max - min) 而不是 (max - min + 1)(会取不到 max,因为乘法结果总停在乘数下方),二是把强制类型转换放错位置。(int) Math.random() * 6 先把 Math.random() 转成 int,那永远是 0,整个表达式就成了 0。强制转换必须包住整个乘法:(int)(Math.random() * 6)

Objects: Instances of Classes

对象(object):类的实例(instance

Class vs Object A class is a blueprint. An object is a specific instance of that class with defined attribute values. Think: Cookie Cutter (class) → Cookie (object).
类 vs 对象 是一份蓝图。对象是该类的一个具体实例,带有具体的属性值。可以类比为:饼干模具(类)→ 饼干(对象)。

Key ideas about class hierarchies (for awareness, not implementation on the AP exam):

关于类层级结构的几个关键概念(AP 考试只要求了解,不要求自己实现):

Superclass: a general class that holds common attributes/behaviors.

Subclass: extends a superclass, inheriting its attributes and behaviors.

Inheritance: the subclass → superclass relationship.

All classes in Java are subclasses of Object.

父类(Superclass):包含公共属性/行为的一般类。

子类(Subclass):扩展父类,继承其属性和行为。

继承:子类 → 父类的关系。

Java 中所有类都是 Object 的子类。

A reference variable stores an object reference (essentially the memory address of the object).

引用变量存储的是对象引用(本质上是该对象的内存地址)。


Object Creation and Storage (Instantiation)

对象的创建与存储(实例化 instantiation

Objects are created using the new keyword followed by a constructor call.

使用 new 关键字加上一次构造方法(constructor调用来创建对象。

// ClassName variableName = new ClassName(arguments);// 类名 变量名 = new 类名(参数列表);
Scanner sc = new Scanner(System.in);
String greeting = new String("Hello");
Constructor A special method with the same name as the class. Sets up initial values. Constructor signature = name + ordered parameter types. Constructors can be overloaded (multiple constructors with different parameter lists).
构造方法(Constructor) 一种特殊的方法,名字与类相同,用于设置初始值。 构造方法签名 = 名字 + 有序的形参类型列表。构造方法可以重载(多个构造方法,形参列表不同)。

Like method calls, constructor calls use call by value, parameters get copies of arguments. A constructor call interrupts sequential flow: statements in the constructor execute first, then control returns.

与普通方法调用一样,构造方法调用也使用按值调用,形参拿到的是实参的副本。构造方法的调用会打断顺序执行:构造方法内的语句先执行,然后控制权再返回。

Reference variables hold either an object reference or null.

引用变量保存的要么是对象引用,要么是 null


Calling Instance Methods

调用实例方法

Instance methods are called on an object using the dot operator.

实例方法(instance method)通过点运算符在某个对象上调用。

String name = "Alice";
int len = name.length();  // instance method call → 5// 实例方法调用 → 5
NullPointerException Calling a method on a null reference throws this run-time error. Always make sure the object exists!
NullPointerExceptionnull 引用上调用方法会在运行时抛出该错误。一定要先确认对象存在!

String Manipulation

字符串(String)操作

String is in java.lang (auto-imported). Strings are immutable, once created, they cannot be changed. Methods return new strings.

String 位于 java.lang(自动导入)。字符串是不可变的(immutable:一旦创建就无法被修改。相关方法返回的都是新的字符串。

Creating Strings

创建字符串

String a = "hello";                      // string literal// 字符串字面量
String b = new String("hello");         // constructor// 构造方法

Concatenation

字符串拼接(concatenation

String full = "AP" + " CSA";   // "AP CSA"// "AP CSA"
int num = 5;
String msg = "Unit " + num;    // "Unit 5", int auto-converts// "Unit 5",int 自动转换
Quick Reference, String Methods
快速参考:String 类方法
MethodReturns
str.length()Number of characters
str.substring(from, to)Chars from index from to to-1
str.substring(from)From index from to end
str.indexOf(s)Index of first occurrence of s; -1 if not found
str.equals(other)true if same sequence of chars
str.compareTo(other)Negative if str<other, 0 if equal, positive if greater
方法返回值
str.length()字符的数量
str.substring(from, to)索引 fromto-1 之间的字符
str.substring(from)从索引 from 到末尾
str.indexOf(s)s 第一次出现的索引;找不到返回 -1
str.equals(other)字符序列相同则为 true
str.compareTo(other)str<other 时为负,相等为 0,大于时为正
StringIndexOutOfBoundsException Indices run from 0 to length() - 1. Accessing outside this range crashes the program.
StringIndexOutOfBoundsException 索引范围是 0length() - 1。访问超出该范围会导致程序崩溃。

Worked Example

例题

String s = "computer";
s.length()              // 8// 8
s.substring(0, 3)       // "com"// "com"
s.substring(3)          // "puter"// "puter"
s.indexOf("put")        // 3// 3
s.indexOf("xyz")        // -1// -1
s.substring(2, 3)       // "m", single char at index 2// "m",索引 2 处的单个字符
toString() & Concatenation with ObjectstoString() 与对象的拼接

When you concatenate a String with any object using +, Java implicitly calls that object's toString() method. Every class inherits toString() from Object, and subclasses often override it to return something meaningful.

当你用 + 把一个 String 与任何对象拼接时,Java 会隐式调用该对象的 toString() 方法。每个类都从 Object 继承了 toString(),子类通常会重写它以返回有意义的内容。

Given String s = "banana";, what does s.substring(1, 4) return?给定 String s = "banana";s.substring(1, 4) 返回什么?
"ban"
"bana"
"ana"
"anan"
Correct! Index 1='a', 2='n', 3='a'. substring(1,4) returns chars at indices 1, 2, 3 → "ana".正确!索引 1='a'、2='n'、3='a'。substring(1,4) 返回索引 1、2、3 处的字符 → "ana"。
Remember: substring(from, to) includes from but excludes to. Indices 1,2,3 → "ana".记住:substring(from, to) 包含 from,但不包含 to。索引 1、2、3 → "ana"。
Worked Example: .equals() vs ==例题:.equals()== 的区别
String a = "hi";
String b = "hi";
String c = new String("hi");

a == b           // true   (string-pool sharing, both point to the same literal)// true   (字符串池共享,两者指向同一个字面量)
a == c           // false  (c is a fresh object on the heap)// false  (c 是堆上新建的对象)
a.equals(c)      // true   (same characters)// true   (字符序列相同)

The rule: use .equals() for content equality on every object type. == on references asks "are these the same object?", which is almost never what an AP MCQ wants when the question says "is the text the same?".

规则:对任何对象类型的内容相等判断都用 .equals()== 作用在引用上问的是"是不是同一个对象?",当 AP 选择题问"文本是否相同?"时,这几乎永远不是它想要的。

AP Trap: Strings are immutable Methods like toUpperCase(), substring(), and replace() return a new String, they don't modify the original. s.toUpperCase(); by itself does nothing useful, you have to write s = s.toUpperCase(); to keep the result. Forgetting to reassign is one of the most common String-manipulation MCQ traps.
AP 陷阱:字符串是不可变的 toUpperCase()substring()replace() 等方法返回的是新的 String,并不会修改原字符串。单独写 s.toUpperCase(); 没有任何效果,必须写成 s = s.toUpperCase(); 才能保留结果。忘了重新赋值,是字符串操作选择题里最常见的陷阱之一。

Unit 1 MCQ Patterns That Show Up Every Year

单元 1 每年都会出现的选择题套路

Unit 1 is mostly tested on the MCQ section. The same handful of patterns reappear in different costumes. If you can spot which pattern a question is testing, you can usually answer it in under 30 seconds.

单元 1 主要在选择题部分被考察。同样的几种套路会换着包装反复出现。只要能认出题目在考哪一种套路,通常 30 秒之内就能作答。

Pattern 1: Integer division hiding inside an expression Look for / with two int operands. If both sides are ints, the result is an int, the fractional part is dropped. Common disguise: storing the result in a double variable, which doesn't change the division itself. (See Topic 1.3.)
套路 1:藏在表达式里的整数除法 留意两侧都是 int 操作数的 /。如果两边都是 int,结果就是 int,小数部分会被丢掉。常见的伪装:把结果存到一个 double 变量里——这并不会改变除法本身。(见小节 1.3。)
Pattern 2: Cast precedence A cast binds tightly. (int) 3.7 + 0.5 is 3.5 (cast hits 3.7 only), not 4. Compare with (int)(3.7 + 0.5), which is 4. (See Topic 1.5.)
套路 2:强制类型转换的优先级 强制类型转换的结合性非常强。(int) 3.7 + 0.5 的结果是 3.5(转换只作用于 3.7),而不是 4。对比 (int)(3.7 + 0.5),那才是 4。(见小节 1.5。)
Pattern 3: Math.random() range derivation Either pick the right formula (int)(Math.random() * (max-min+1)) + min or read a given expression and back-solve the inclusive range. Watch for off-by-one in the multiplier and for casts in the wrong spot. (See Topic 1.11.)
套路 3:Math.random() 区间推导 要么挑出正确的公式 (int)(Math.random() * (max-min+1)) + min,要么读懂给定的表达式、反推它能取到的闭区间。小心乘数上的差一错误,以及强制类型转换的位置不对。(见小节 1.11。)
Pattern 4: String == vs .equals() If the question stores strings two different ways (one literal, one new String(...)), == can be false even though the text is identical. .equals() is the AP-correct answer for content comparison. (See Topic 1.15.)
套路 4:String 的 ==.equals() 如果题目用两种方式存放字符串(一个是字面量,另一个是 new String(...)),即使文字完全相同,== 也可能是 false。在 AP 中,比较内容的正确答案是 .equals()。(见小节 1.15。)
Pattern 5: substring index bounds s.substring(a, b) includes index a, excludes index b. Length of the result is b - a. s.substring(a) runs to the end. Always check that 0 ≤ a ≤ b ≤ s.length(), otherwise it crashes.
套路 5:substring 的索引边界 s.substring(a, b) 包含索引 a、不包含索引 b。结果的长度是 b - as.substring(a) 一直取到末尾。务必检查 0 ≤ a ≤ b ≤ s.length(),否则程序会崩溃。
Pattern 6: NullPointerException on uninitialized reference Calling any instance method on a null reference crashes the program. If a code segment declares String s; but never assigns it, then s.length() throws NullPointerException. Watch for the missing new.
套路 6:在未初始化的引用上发生 NullPointerExceptionnull 引用上调用任何实例方法都会让程序崩溃。如果一段代码只写了 String s; 却始终没有给它赋值,那么 s.length() 会抛出 NullPointerException。留意缺失的 new

Flashcards, Click to Flip

闪卡(点击翻面)

What is an algorithm?什么是算法?
A step-by-step process for completing a task or solving a problem.完成任务或解决问题的一步一步的过程。
3 primitive types in AP CSA?AP CSA 的 3 种基本类型?
int, double, boolean
What does 7 / 2 equal?7 / 2 等于多少?
3, integer division truncates the decimal.3,整数除法会截断小数部分。
Casting (int) 9.8 gives?(int) 9.8 转换后是?
9, truncation, not rounding.9,是截断,不是四舍五入。
Class method vs Instance method?类方法与实例方法的区别?
Class (static): called on the class.
Instance: called on an object.
类方法(静态):在类上调用。
实例方法:在对象上调用。
What does Math.random() return?Math.random() 返回什么?
A double ≥ 0.0 and < 1.0一个 ≥ 0.0 且 < 1.0 的 double
Strings are ___?字符串是 ___?
Immutable, once created, their content cannot change.不可变的,一旦创建,内容就无法改变。
s.substring(2, 5) returns what indices?s.substring(2, 5) 返回哪些索引处的字符?
Characters at indices 2, 3, 4 (includes from, excludes to).索引 2、3、4 处的字符(含 from,不含 to)。
NullPointerException
Thrown when you call a method on a reference that is null.当你在一个值为 null 的引用上调用方法时抛出。
Precondition vs Postcondition?前置条件与后置条件的区别?
Pre: must be true before method runs.
Post: guaranteed true after method runs.
前置条件:方法运行必须为真。
后置条件:方法运行保证为真。

Unit 1, Practice Quiz

单元 1:练习小测

1. What is the output of System.out.println(3 + 4 + "Hi" + 3 + 4);?1. System.out.println(3 + 4 + "Hi" + 3 + 4); 的输出是什么?
34Hi34
3 + 4 + Hi + 3 + 4
7Hi34
7Hi7
Correct! Left to right: 3+4=7 (int math), then 7+"Hi"="7Hi" (string concat), then "7Hi"+3="7Hi3", then "7Hi3"+4="7Hi34".正确!从左到右:3+4=7(整数运算),然后 7+"Hi"="7Hi"(字符串拼接),接着 "7Hi"+3="7Hi3",最后 "7Hi3"+4="7Hi34"。
Evaluate left to right: 3+4=7, then 7+"Hi"="7Hi" (switching to string concat), then append 3 and 4 as strings → "7Hi34".从左到右求值:3+4=7,然后 7+"Hi"="7Hi"(切换为字符串拼接),再把 3 和 4 当作字符串追加 → "7Hi34"。
2. Which correctly creates a random integer from 1 to 100?2. 哪一项正确生成 1 到 100 之间的随机整数?
(int)(Math.random() * 100)
(int)(Math.random() * 100) + 1
(int)(Math.random() * 101)
(int)(Math.random() * 99) + 1
Correct! Math.random()*100 gives [0, 100), cast to int gives 0–99, + 1 gives 1–100.正确!Math.random()*100 取值在 [0, 100),转成 int 得到 0–99,再加 1 得到 1–100。
Formula: (int)(Math.random() * range) + min where range = 100 and min = 1.公式:(int)(Math.random() * range) + min,其中 range = 100,min = 1。
3. What does the following code print?
String s = "APCS"; System.out.println(s.substring(1, 3));
3. 下面这段代码打印什么?
String s = "APCS"; System.out.println(s.substring(1, 3));
PC
PCS
AP
APC
Correct! Index 1='P', index 2='C'. substring(1,3) → "PC" (3 is exclusive).正确!索引 1='P'、索引 2='C'。substring(1,3) → "PC"(3 是开区间)。
substring(1,3) returns characters at indices 1 and 2 → "PC".substring(1,3) 返回索引 1 和 2 处的字符 → "PC"。
4. Which is a logic error?4. 下列哪一项是逻辑错误?
Missing semicolon缺少分号
Dividing by zero at run-time运行时除以零
Using an undeclared variable使用未声明的变量
Using + instead of − in a formula在公式中把 − 写成了 +
Correct! Logic errors produce wrong results but no compiler/runtime errors. Using the wrong operator is a classic logic error.正确!逻辑错误会让结果出错,但既不会有编译错误也不会有运行时错误。用错运算符是典型的逻辑错误。
A logic error makes the program produce incorrect output without crashing. Using the wrong operator (+ instead of −) is a logic error.逻辑错误会让程序输出不正确,但不会崩溃。用错运算符(把 − 写成 +)就是一种逻辑错误。
5. What value is stored after: int x = 5; x %= 3;?5. 执行 int x = 5; x %= 3; 之后存储的值是多少?
1.67
3
2
0
Correct! x %= 3 means x = x % 3 = 5 % 3 = 2.正确!x %= 3 等同于 x = x % 3 = 5 % 3 = 2。
x %= 3 is the same as x = 5 % 3. 5 divided by 3 has remainder 2.x %= 3 等同于 x = 5 % 3。5 除以 3 的余数是 2。

AP-Style Practice Problems

AP 风格练习题

15 exam-level multiple-choice questions (3 medium · 12 hard), code-trace heavy with realistic distractors and fully worked solutions. Built for top-score prep — go here after you've worked through the notes and the in-page quiz above.

15 道考试级别的选择题(3 道中等难度 · 12 道高难度),以代码跟踪为主,含真实的干扰项和完整的解题过程。专为冲刺高分准备——在你看完本页笔记并做完上方的小测之后再来。

Practice Problems →练习题 →

鼎睿学苑 · Dingrui Scholars

AP Computer Science A, Unit 1: Using Objects & Methods · 2026 Edition

AP 计算机科学 A,单元 1:使用对象与方法 · 2026 版