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 类,以及创建和使用对象。
Introduction to Algorithms, Programming, and Compilers
算法、编程与编译器入门
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 Type | When Detected | Example |
|---|---|---|
| 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)
一种特定的运行时错误,会中断程序的正常流程。编译器无法捕获它。
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)
| Type | What It Stores | Example |
|---|---|---|
int | Integers (whole numbers) | int age = 17; |
double | Real numbers (decimals) | double gpa = 3.85; |
boolean | true or false | boolean passed = true; |
| 类型 | 存储内容 | 示例 |
|---|---|---|
int | 整数(整型数) | int age = 17; |
double | 实数(带小数) | double gpa = 3.85; |
boolean | true 或 false | boolean passed = true; |
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 对象的地址
true) or off (false), a perfect fit for boolean.正确!电灯开关只有开(true)或关(false)两种状态,正好用 boolean。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"。
| Escape | Meaning | Example Output |
|---|---|---|
\" | Double quote | "She said \"hi\"" → She said "hi" |
\\ | Backslash | "C:\\Users" → C:\Users |
\n | Newline | "Line1\nLine2" → two lines |
| 转义序列 | 含义 | 输出示例 |
|---|---|---|
\" | 双引号 | "She said \"hi\"" → She said "hi" |
\\ | 反斜杠 | "C:\\Users" → C:\Users |
\n | 换行 | "Line1\nLine2" → 分成两行 |
Arithmetic Operators
算术运算符(operator)
| Operator | Operation | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division | 7 / 3 | 2 (int!) |
% | Remainder | 7 % 3 | 1 |
| 运算符 | 运算 | 示例 | 结果 |
|---|---|---|---|
+ | 加法 | 7 + 3 | 10 |
- | 减法 | 7 - 3 | 4 |
* | 乘法 | 7 * 3 | 21 |
/ | 除法 | 7 / 3 | 2(整型!) |
% | 取余 | 7 % 3 | 1 |
7 / 2 → 3 (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 / 2 → 3(不是 3.5!)。两个操作数都是 int,所以结果也是 int,小数部分会被丢掉。要得到 3.5,至少要有一个 double:7.0 / 2。
* / % happen before + - (left to right). Parentheses override precedence.
precedence)
* / % 先于 + -(从左到右)。括号可以覆盖默认优先级。
int by 0 throws this exception at run-time.
int 除以 0 会在运行时抛出该异常(exception)。
13 / 5 + 13 % 5?13 / 5 + 13 % 5 的值是多少?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。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)。
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.
a / b 的结果类型取决于 a 和 b 的类型,而不是你把结果存到哪里。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,右边先求值
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
int → double when needed (e.g., assigning an int to a double variable).
int 提升为 double(例如,把一个 int 赋值给一个 double 变量时)。
(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):结果会以不可预测的方式回卷。
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。
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。
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.
int 和 double 混在一起的表达式都会按 double 计算。3 + 1.0 是 4.0,而不是 4。要把结果赋值给一个 int 变量,必须使用显式类型转换,而且转换会把小数部分截断。
Compound Assignment Operators
复合赋值运算符(operator)
| Operator | Equivalent To | Example |
|---|---|---|
x += 5 | x = x + 5 | |
x -= 3 | x = x - 3 | |
x *= 2 | x = x * 2 | |
x /= 4 | x = x / 4 | |
x %= 3 | x = x % 3 | |
x++ | x = x + 1 | Post-increment |
x-- | x = x - 1 | Post-decrement |
| 运算符 | 等价于 | 说明 |
|---|---|---|
x += 5 | x = x + 5 | |
x -= 3 | x = x - 3 | |
x *= 2 | x = x * 2 | |
x /= 4 | x = x / 4 | |
x %= 3 | x = 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(应用程序接口)是一份文档,告诉你如何使用这些类。
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 文档 */
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)是一段有名字的代码块,只有在被调用时才会执行。过程抽象:你只需要知道一个方法做什么就能使用它,而不必知道它怎么做。
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 方法
| void | Non-void | |
|---|---|---|
| Returns a value? | No | Yes |
| Used in expressions? | No, standalone call | Yes, store/use the return value |
| void | 非 void | |
|---|---|---|
| 是否返回值? | 否 | 是 |
| 能用在表达式中吗? | 不能,只作为独立调用 | 能,可保存或使用返回值 |
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(自动可用)。只包含静态方法,不需要创建对象就能使用。
| Method | Returns |
|---|---|
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
(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。(int)(Math.random() * 6) + 5.范围 = max − min + 1 = 6。公式是 (int)(Math.random() * 6) + 5。Goal: pick a random integer from min to max inclusive.
目标:从 min 到 max(含端点)取一个随机整数。
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;
(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).
(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)
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");
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
null reference throws this run-time error. Always make sure the object exists!
null 引用上调用方法会在运行时抛出该错误。一定要先确认对象存在!
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 自动转换
| Method | Returns |
|---|---|
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) | 索引 from 到 to-1 之间的字符 |
str.substring(from) | 从索引 from 到末尾 |
str.indexOf(s) | s 第一次出现的索引;找不到返回 -1 |
str.equals(other) | 字符序列相同则为 true |
str.compareTo(other) | str<other 时为负,相等为 0,大于时为正 |
0 to length() - 1. Accessing outside this range crashes the program.
0 到 length() - 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(),子类通常会重写它以返回有意义的内容。
String s = "banana";, what does s.substring(1, 4) return?给定 String s = "banana";,s.substring(1, 4) 返回什么?substring(1,4) returns chars at indices 1, 2, 3 → "ana".正确!索引 1='a'、2='n'、3='a'。substring(1,4) 返回索引 1、2、3 处的字符 → "ana"。substring(from, to) includes from but excludes to. Indices 1,2,3 → "ana".记住:substring(from, to) 包含 from,但不包含 to。索引 1、2、3 → "ana"。.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 选择题问"文本是否相同?"时,这几乎永远不是它想要的。
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.
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 秒之内就能作答。
/ 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.)
/。如果两边都是 int,结果就是 int,小数部分会被丢掉。常见的伪装:把结果存到一个 double 变量里——这并不会改变除法本身。(见小节 1.3。)
(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.)
(int) 3.7 + 0.5 的结果是 3.5(转换只作用于 3.7),而不是 4。对比 (int)(3.7 + 0.5),那才是 4。(见小节 1.5。)
(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.)
(int)(Math.random() * (max-min+1)) + min,要么读懂给定的表达式、反推它能取到的闭区间。小心乘数上的差一错误,以及强制类型转换的位置不对。(见小节 1.11。)
== 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.)
== 与 .equals()
如果题目用两种方式存放字符串(一个是字面量,另一个是 new String(...)),即使文字完全相同,== 也可能是 false。在 AP 中,比较内容的正确答案是 .equals()。(见小节 1.15。)
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.
s.substring(a, b) 包含索引 a、不包含索引 b。结果的长度是 b - a。s.substring(a) 一直取到末尾。务必检查 0 ≤ a ≤ b ≤ s.length(),否则程序会崩溃。
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.
null 引用上调用任何实例方法都会让程序崩溃。如果一段代码只写了 String s; 却始终没有给它赋值,那么 s.length() 会抛出 NullPointerException。留意缺失的 new。
Flashcards, Click to Flip
闪卡(点击翻面)
int, double, boolean7 / 2 equal?7 / 2 等于多少?3, integer division truncates the decimal.3,整数除法会截断小数部分。(int) 9.8 gives?(int) 9.8 转换后是?9, truncation, not rounding.9,是截断,不是四舍五入。Instance: called on an object.类方法(静态):在类上调用。
实例方法:在对象上调用。
Math.random() return?Math.random() 返回什么?double ≥ 0.0 and < 1.0一个 ≥ 0.0 且 < 1.0 的 double。s.substring(2, 5) returns what indices?s.substring(2, 5) 返回哪些索引处的字符?from, excludes to).索引 2、3、4 处的字符(含 from,不含 to)。null.当你在一个值为 null 的引用上调用方法时抛出。Post: guaranteed true after method runs.前置条件:方法运行前必须为真。
后置条件:方法运行后保证为真。
Unit 1, Practice Quiz
单元 1:练习小测
System.out.println(3 + 4 + "Hi" + 3 + 4);?1. System.out.println(3 + 4 + "Hi" + 3 + 4); 的输出是什么?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。(int)(Math.random() * range) + min where range = 100 and min = 1.公式:(int)(Math.random() * range) + min,其中 range = 100,min = 1。String s = "APCS"; System.out.println(s.substring(1, 3));3. 下面这段代码打印什么?String s = "APCS"; System.out.println(s.substring(1, 3));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"。int x = 5; x %= 3;?5. 执行 int x = 5; x %= 3; 之后存储的值是多少?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 道高难度),以代码跟踪为主,含真实的干扰项和完整的解题过程。专为冲刺高分准备——在你看完本页笔记并做完上方的小测之后再来。
鼎睿学苑 · Dingrui Scholars
AP Computer Science A, Unit 1: Using Objects & Methods · 2026 Edition
AP 计算机科学 A,单元 1:使用对象与方法 · 2026 版