Skip to content · ⁨コンテンツへスキップ⁩
Subjects · ⁨科目⁩

AP Computer Science A · ⁨APコンピュータサイエンスA⁩

Tips · ⁨ヒント⁩

AP Computer Science A is a Java course: objects and classes, primitive types and control flow, writing classes, arrays and ArrayLists, 2D arrays, inheritance and polymorphism, and recursion. It is a first programming course taught with real object-oriented code, not pseudocode.

All four free-response questions are hand-written Java. No compiler will catch a missing semicolon or a wrong return type for you, so write code on paper during revision — it is a different skill from typing it.

Arrays and ArrayLists are the most-tested topic. Being fluent with traversal, insertion and removal, and knowing which index shifts when you remove an element, pays back more than any other single hour of practice.

Notes cover the CED units in Java, with runnable examples you can edit in the browser. Past FRQs and scoring guidelines are in the library — all four are code-writing questions, so the worked answers are complete methods rather than fragments.

  • 1

    Using Objects and Methods · ⁨物体と手法の使用⁩

    Watch lesson · ⁨レッスンを視聴⁩
    1.1

    Introduction to Algorithms, Programming, and Compilers

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 1.1.A: Represent patterns and algorithms found in everyday life using written language or diagrams.

    • 1.1.A.1 Algorithms define step-by-step processes to follow when completing a task or solving a problem. These algorithms can be represented using written language or diagrams.
    • 1.1.A.2 Sequencing defines an order for when steps in a process are completed. Steps in a process are completed one at a time.

    Learning Objective 1.1.B: Explain the code compilation and execution process.

    • 1.1.B.1 Code can be written in any text editor; however, an integrated development environment (IDE) is often used to write programs because it provides tools for a programmer to write, compile, and run code.
    • 1.1.B.2 A compiler checks code for some errors. Errors detectable by the compiler need to be fixed before the program can be run.

    Learning Objective 1.1.C: Identify types of programming errors.

    • 1.1.C.1 A syntax error is a mistake in the program where the rules of the programming language are not followed. These errors are detected by the compiler.
    • 1.1.C.2 A logic error is a mistake in the algorithm or program that causes it to behave incorrectly or unexpectedly. These errors are detected by testing the program with specific data to see if it produces the expected outcome.
    • 1.1.C.3 A run-time error is a mistake in the program that occurs during the execution of a program. Run-time errors typically cause the program to terminate abnormally.
    • 1.1.C.4 An exception is a type of run-time error that occurs as a result of an unexpected error that was not detected by the compiler. It interrupts the normal flow of the program's execution.
    日本語

    学習目標 1.1.A: 日常に見られるパターンやアルゴリズムを、言語表現または図表を用いて表現せよ。

    • 1.1.A.1 アルゴリズム は、タスクの実行や問題解決の際に行うべき手順を段階的に定義する。これらのアルゴリズムは、言語表現または図表で表すことができる。
    • 1.1.A.2 シーケンシング は、プロセス中のステップが完了される順序を定義する。プロセス中のステップは、1つずつ順に完了される。

    学習目標 1.1.B: コードのコンパイルおよび実行プロセスを説明せよ。

    • 1.1.B.1 コードはどのようなテキストエディタでも書けるが、統合開発環境 (IDE) がよく用いられるのは、プログラマがコードを書き、コンパイルし、実行するためのツールを提供するからである。
    • 1.1.B.2 コンパイラ は、コードに何らかのエラーが含まれているかチェックする。コンパイラによって検出可能なエラーは、プログラムを実行する前に修正されなければならない。

    学習目標 1.1.C: プログラミングエラーの種類を識別せよ。

    • 1.1.C.1 構文エラー は、プログラミング言語のルールに従っていないため、プログラム中に生じるミスである。これらのエラーはコンパイラによって検出される。
    • 1.1.C.2 論理エラー は、アルゴリズムまたはプログラムに含まれるミスであり、予期しない、あるいは誤った振る舞いを引き起こす。これらのエラーは、特定のデータでプログラムをテストして、期待される結果が得られるかどうかを確認することで検出される。
    • 1.1.C.3 ランタイムエラー は、プログラムの実行中に生じるプログラムのミスである。ランタイムエラーは通常、プログラムが異常に終了することを引き起こす。
    • 1.1.C.4 例外 は、コンパイラによって検出されない予期せぬエラーの結果として生じるランタイムエラーの一種である。これはプログラムの通常の実行フローを中断する。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語
    Source code on a workstation — programs are written, compiled, and run as precise instructions
    Source code on a workstation — programs are written, compiled, and run as precise instructions

    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 line
    A compiler translates the whole program at once; an interpreter runs it line by line
    Several computer processor chips seen from below
    Your Java program is compiled to instructions a CPU like one of these actually runs
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    algorithm/ˈælɡərɪθəm/ アルゴリズム
    program/ˈprəʊɡræm/ プログラム
    compiled/kəmˈpaɪld/ 統合された
    compiler/kəmˈpaɪlə/ コンパイラ
    syntax error/ˈsɪntæks ˈerə/ 構文エラー
    logic error/ˈlɒdʒɪk ˈerə/ ロジックエラー
    1.2

    Variables and Data Types

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 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, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.
      • Exclusion statement: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam.
    • 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.
    日本語

    学習目標 1.2.A: 特定の仕様に対して最も適切なデータタイプのカテゴリーを特定する。

    • 1.2.A.1 データタイプとは、一連の値とそれらに対する対応する操作のセットのことです。データタイプは、プリミティブまたは参照のいずれかに分類されます。
    • 1.2.A.2 このコースで使用されるプリミティブデータタイプは、数値およびブール値に対する一連の値と対応する操作を定義しています。
    • 1.2.A.3 参照タイプは、プリミティブタイプではないオブジェクトを定義するために使用されます。

    学習目標 1.2.B: 数値およびブール値を格納するための変数を宣言するコードを作成する。

    • 1.2.B.1 このコースで使用される3つのプリミティブデータタイプは int, double, boolean です。 int 値は整数です。 double 値は実数です。 boolean 値は true または false のどちらかです。
      • 除外事項: 他の5つのプリミティブデータタイプ (long, short, byte, float, char) は、APコンピュータサイエンスAコースおよび試験の範囲外です。
    • 1.2.B.2 変数とは、値を保持する格納場所であり、プログラム実行中に値が変更できる可能性があります。すべての変数は名前と関連付けられたデータタイプを持っています。プリミティブタイプの変数は、そのタイプからのプリミティブ値を保持します。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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), and boolean (true/false). Declare with the type first:

    日本語

    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), and boolean (true/false). Declare with the type first:

    Java's basic data types, each storing a different kind of value
    Java's basic data types, each storing a different kind of value
    int score = 90;
    double price = 4.99;
    boolean passed = true;
    
    Explore · ⁨探索⁩

    Explore 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 score overwrites the old number rather than making a new box.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    variable/ˈveərɪəbl/ 変数
    type/taɪp/ タイプ(文字)
    primitive types/ˈprɪmɪtɪv taɪps/ プリミティブ型
    1.3

    Expressions and Output

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential Knowledge

    1.3.A
    Develop code to generate output and determine the result that would be displayed.

    • 1.3.A.1 System.out.print and System.out.println display information on the computer display. System.out.println moves the cursor to a new line after the information has been displayed, while System.out.print does 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 int and double.
    • 1.3.C.2 The arithmetic operators consist of addition +, subtraction -, multiplication *, division /, and remainder %. An arithmetic operation that uses two int values will evaluate to an int value. An arithmetic operation that uses at least one double value will evaluate to a double value.
      • 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 int values, the result is only the integer portion of the quotient. When dividing numeric values that use at least one double value, the result is the quotient.
    • 1.3.C.4 The remainder operator % is used to compute the remainder when one number a is divided by another number b.
      • Exclusion statement: The use of values less than 0 for a and the use of values less than or equal to 0 for b is outside the scope of the AP Computer Science A course and exam.
    • 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 double is outside the scope of the AP Computer Science A course and exam.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An expression 表达式 combines values and operators to compute a result: + - * / and % (modulus 取模, the remainder). Integer division truncates: 7 / 2 is 3, while 7 % 2 is 1. Operator precedence follows math (*,/,% before +,-). Print with:

    Dividing an integer by the integer 0 (like 7 / 0) is not allowed and crashes at run time with an ArithmeticException. Inside a string, a backslash marks an escape sequence 转义序列: \" prints a double quote, \\ a single backslash, and \n starts a new line – so System.out.println("She said \"hi\""); prints She said "hi".

    日本語

    An expression 表达式 combines values and operators to compute a result: + - * / and % (modulus 取模, the remainder). Integer division truncates: 7 / 2 is 3, while 7 % 2 is 1. Operator precedence follows math (*,/,% before +,-). Print with:

    System.out.print("no newline");
    System.out.println("with newline");
    

    Dividing an integer by the integer 0 (like 7 / 0) is not allowed and crashes at run time with an ArithmeticException. Inside a string, a backslash marks an escape sequence 转义序列: \" prints a double quote, \\ a single backslash, and \n starts a new line – so System.out.println("She said \"hi\""); prints She said "hi".

    Explore · ⁨探索⁩

    Explore the order of operations step by step

    Java applies *, /, % before + and -, working left to right. Watch each step and see why 2 + 3 * 4 is $14$, not $20$ — the multiplication happens first.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    expression/ekˈspreʃn/ 表現
    modulus/ˈmɒdjʊləs/ 絶対値
    escape sequence/eˈskeɪp ˈsiːkwəns/ エスケープシーケンス
    1.4

    Assignment Statements and Input

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 null if there is no object. The literal null is 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; or a[i += 5]) is outside the scope of the AP Computer Science A course and exam.
    • 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.

    Learning Objective 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 Scanner class 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.
    日本語

    学習目標 1.4.A: 式を含む代入文のためのコードを作成し、これらの文によって変数に格納される値を決定する。

    • 1.4.A.1 変数は式内で使用される前に必ず値を割り当てられる必要があります。その値は互換のあるデータ型である必要があります。変数は最初に値が割り当てられたときに初期化されます。参照型には、新しいオブジェクトまたはオブジェクトがない場合は null を割り当てることができます。リテラル null は、参照がどのオブジェクトとも関連していないことを示すために使用される特別な値です。
    • 1.4.A.2 代入演算子 = を使用すると、プログラムが変数に格納されている値を初期化または変更できます。右側の式の値が左側の変数に格納されます。
      • 除外事項: 式内での代入演算子(例:a = b = 4; や a[i += 5])の使用は、APコンピュータサイエンスAコースおよび試験の範囲外です。
    • 1.4.A.3 実行中、式は単一の値を生成するために評価されます。式の値は、式の評価に基づいたタイプを持ちます。

    学習目標 1.4.B: 入力を読み取るためのコードを作成する。

    • 1.4.B.1 入力は触覚的、音声、視覚的、またはテキストなど、さまざまな形式で提供されることがあります。Scanner クラスはキーボードからのテキスト入力を取得する方法の一つです。
      • 除外事項: ユーザーからの特定の形式の入力は、APコンピュータサイエンスAコースおよび試験の範囲外です。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An assignment 赋值 x = expr; evaluates the right side and stores it in the left variable. Read input with a Scanner:

    日本語

    An assignment 赋值 x = expr; evaluates the right side and stores it in the left variable. Read input with a Scanner:

    Scanner in = new Scanner(System.in);
    int age = in.nextInt();
    String name = in.next();
    
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    assignment/əˈsaɪnmənt/ 代入
    1.5

    Casting and Range of Variables

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 a double value to an int value (or vice versa).
    • 1.5.A.2 Casting a double value to an int value causes the digits to the right of the decimal point to be truncated.
    • 1.5.A.3 Some code causes int values to be automatically cast (widened) to double values.
    • 1.5.A.4 Values of type double can be rounded to the nearest integer by (int)(x + 0.5) for non-negative numbers or (int)(x - 0.5) for negative numbers.

    Learning Objective 1.5.B: Describe conditions when an integer expression evaluates to a value out of range.

    • 1.5.B.1 The constant Integer.MAX_VALUE holds the value of the largest possible int value. The constant Integer.MIN_VALUE holds the value of the smallest possible int value.
    • 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, an int value must be in the range from Integer.MIN_VALUE to Integer.MAX_VALUE inclusive.
    • 1.5.B.3 If an expression would evaluate to an int value outside of the allowed range, an integer overflow occurs. The result is an int value in the allowed range but not necessarily the value expected.

    Learning Objective 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 double that 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, use int values.
      • 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.
    日本語

    学習目標 1.5.A: 算術式内でプリミティブ値を異なるプリミティブ型にキャストするためのコードを作成し、結果として生成される値を決定する。

    • 1.5.A.1 キャスト演算子 (int) と (double) を使用して、double の値を int の値に変換したり(逆も可能)、変換したりできます。
    • 1.5.A.2 double の値を int の値にキャストすると、小数点以下の桁が切り捨てられます。
    • 1.5.A.3 一部のコードでは、int の値が自動的にdouble の値に拡張(ワイドニング)されます。
    • 1.5.A.4 double 型の値は、非負の数字に対して (int)(x + 0.5) で、負の数字に対して (int)(x - 0.5) で四捨五入され、最も近い整数になります。

    学習目標 1.5.B: 整数式が範囲外の値に評価される条件を説明する。

    • 1.5.B.1 定数 Integer.MAX_VALUE は、可能な最大の int の値を表します。定数 Integer.MIN_VALUE は、可能な最小の int の値を表します。
    • 1.5.B.2 Javaにおける整数値は、类型为 int の値として表現され、有限の量(4バイト)のメモリに格納されます。したがって、int の値は Integer.MIN_VALUE から Integer.MAX_VALUE までの範囲内(境界値含む)である必要があります。
    • 1.5.B.3 式が許容範囲外の int の値に評価されようとすると、整数オーバーフローが発生します。結果は許容範囲内の int の値となりますが、必ずしも期待される値とは限りません。

    学習目標 1.5.C: 式の精度を制限する条件を説明する。

    • 1.5.C.1 コンピュータはデータ型に基づき、データを格納するために指定された量のメモリを割り当てます。式が割り当てられたメモリの量に格納できる精度よりも高い double に評価されようとすると、丸め誤差が発生します。結果は表現可能な値に丸められます。自然に生じる丸め誤差を避けるため、int の値を使用してください。
      • 除外事項: 丸め誤差を避けるために使用できる他の特別な小数型データは、APコンピュータサイエンスAコースおよび試験の範囲外です。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    int range, overflow and truncation

    Each type has a fixed range; an int overflows past about 2.1 billion. Casting 类型转换 converts between types. Widening (int to double) is automatic; narrowing needs an explicit cast, which truncates (does not round):

    Exam skill: watch for integer division producing a truncated result when a decimal was expected – cast one operand to double first.

    Worked example. Trace each expression:

    • 7 / 2 → 3 (both int, so division truncates);
    • 7.0 / 2 → 3.5 (one double forces real division);
    • 7 % 2 → 1 (the remainder);
    • (double) 7 / 2 → 3.5 (the cast binds tighter than /, so it is 7.0 / 2);
    • (double) (7 / 2) → 3.0 (the parentheses compute 7 / 2 = 3 in int first, then widen).

    The last two look alike but differ – the position of the cast decides whether the truncation happens.

    日本語
    int range, overflow and truncation

    Each type has a fixed range; an int overflows past about 2.1 billion. Casting 类型转换 converts between types. Widening (int to double) 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, truncated
    

    Exam skill: watch for integer division producing a truncated result when a decimal was expected – cast one operand to double first.

    Worked example. Trace each expression:

    • 7 / 2 → 3 (both int, so division truncates);
    • 7.0 / 2 → 3.5 (one double forces real division);
    • 7 % 2 → 1 (the remainder);
    • (double) 7 / 2 → 3.5 (the cast binds tighter than /, so it is 7.0 / 2);
    • (double) (7 / 2) → 3.0 (the parentheses compute 7 / 2 = 3 in int first, then widen).

    The last two look alike but differ – the position of the cast decides whether the truncation happens.

    Explore · ⁨探索⁩

    Why int and double store numbers differently

    An int holds only whole numbers in a fixed range; a double stores a mantissa and an exponent, trading exactness for a huge range. Casting double→int throws away the fraction, and a value past an int's range overflows.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Casting/ˈkæstɪŋ/ キャスト
    1.6

    Compound Assignment Operators

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 add 1 or subtract 1 from 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.
    日本語

    学習目標 1.6.A: 複合代入演算子を含む代入文のためのコードを作成し、結果として変数に格納される値を決定する。

    • 1.6.A.1 複合代入演算子 +=、-=、*=、/=、%= は、数値式における代入演算子の代わりに使用できます。複合代入演算子は、左側の値と右側の値の間で指定された算術演算を実行し、その結果を左側の変数に割り当てます。
    • 1.6.A.2 後置増分演算子 ++ と後置減分演算子 -- は、数値変数に格納されている値に 1 を加えたり、1 を引いたりするために使用されます。新しい値が変数に割り当てられます。
      • 除外事項: AP Computer Science A のコースおよび試験の範囲外である: 先置形式(例:++x)でのインクリメント・デクリメント演算子の使用。他の式内(例:arr[x++])でのインクリメント・デクリメント演算子の使用。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    Shorthands combine an operation with assignment: x += 5 means x = x + 5; likewise -=, *=, /=, %=. The increment and decrement operators x++ and x-- add or subtract one.

    1.7

    Application Program Interface (API) and Libraries

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 1.7.A: API に含まれるライブラリ内のクラスに見られる属性と振る舞いを特定する。

    • 1.7.A.1 ライブラリ はクラスの集合体である。アプリケーション・プログラミング・インターフェース (API) の仕様書は、プログラマーがこれらのクラス如何使用するかを指示する。API 仕様書やライブラリに含まれるドキュメントは、API で定義されたクラスの属性や振る舞いを理解するために不可欠である。クラス は特定の参照型を定義する。API やライブラリ内のクラスはパッケージにグループ化される。既存のクラスやクラス・ライブラリを用いてオブジェクトを作成できる。
    • 1.7.A.2 属性 はクラスに関連するデータを指し、変数に格納される。振る舞い はクラスのインスタンスができること(またはそれらに対して行われること)を指し、メソッドによって定義される。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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 抽象.

    日本語

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    library/ˈlaɪbrəri/ ライブラリ
    abstraction/əbˈstrækʃn/ 抽象化
    Interface/ˈɪntəfeɪs/ インターフェース
    1.8

    Documentation with Comments

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 1.8.A: コメントを通じてコードの機能と使い方を説明する。

    • 1.8.A.1 コメント は、元のプログラマーや他のプログラマーがコードおよびその機能を理解するために記述されるが、コンパイラには無視され、プログラム実行時には実行されない。Javaにおける3種類のコメントとして、/* */(ブロックコメントを生成)、//(1行分のコメントを生成)、および /** */(Javadocコメントであり、API ドキュメント作成に使用される)がある。
    • 1.8.A.2 前置条件 とは、メソッドが期待通り動作するために、メソッド実行直前に真でなければならない条件のことである。メソッドが前置条件が満たされているかを検証するという期待はない。
    • 1.8.A.3 後条件 (postcondition) とは、メソッドの実行後に常に真でなければならない条件のことである。後条件は、返される値やオブジェクトの属性の現在の値という観点から、実行の結果を説明する。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Comments/ˈkɒments/ コメント
    1.9

    Method Signatures

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 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.
    日本語

    学習目標 1.9.A: ドキュメンテーションとメソッド・シグネチャに基づき、適切なメソッドを特定する。

    • 1.9.A.1 メソッド は、呼び出されたときにのみ実行される名付けられたコードのブロックである。コードのブロック は、波括弧で囲まれた任意のコードセクションを指す。手続的抽象 は、メソッドがどのように書かれているかは知らなくても、メソッドが何をするかを知っているだけで、プログラマーがメソッドを使用できるようにする。
    • 1.9.A.2 パラメータ とは、メソッドまたはコンストラクタのヘッダーで宣言された変数であり、メソッド本体内で使用できる。これにより、値や引数をメソッドまたはコンストラクタへ渡して使用できる。パラメータを持つメソッドのメソッド・シグネチャ は、メソッド名とパラメータ型の順序付きリストからなる。パラメータを持たないメソッドのメソッド・シグネチャは、メソッド名と空のパラメータリストからなる。

    学習目標 1.9.B: メソッドの呼び出し方法を説明する。

    • 1.9.B.1 void メソッド は戻り値を持たないため、式の一部として呼び出されることはない。
    • 1.9.B.2 非void メソッド は、ヘッダーの戻り型と同じタイプの値を返す。非void メソッドを呼び出す際に戻り値を使用するには、変数に格納するか、式の一部として使用する必要がある。
    • 1.9.B.3 引数 とは、メソッドが呼び出されたときにメソッドへ渡される値である。メソッドへ渡される引数は、メソッド・シグネチャのパラメータリストで識別された型に対して、個数と順序が互換性でなければならない。メソッドを呼び出す際、引数は値渡しによって渡される。値渡し とは、引数のコピーでパラメータを初期化することである。
    • 1.9.B.4 複数のメソッドが存在し、名前が同じだがシグネチャが異なる場合、それらのメソッドはオーバーロードされていると言われる。
    • 1.9.B.5 メソッド・コール は文の順次実行を中断し、メソッド内の文を先に実行してから続きを処理させる。メソッド内の最終文が実行されたり、return 文が実行されたりすると、制御の流れはメソッドが呼び出された直後のポイントに戻される。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    A method signature 方法签名 is a method's name plus its parameter types, e.g. nextInt() or substring(int, int). To call a method you must supply arguments 实参 that match the parameters in number, type, and order. The method header (the full declaration) also states the return type – the type of value the method gives back (void if none) – but the return type is not part of the signature, which is why two methods cannot differ by return type alone.

    日本語

    A method signature 方法签名 is a method's name plus its parameter types, e.g. nextInt() or substring(int, int). To call a method you must supply arguments 实参 that match the parameters in number, type, and order. The method header (the full declaration) also states the return type – the type of value the method gives back (void if none) – but the return type is not part of the signature, which is why two methods cannot differ by return type alone.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    method signature/ˈmeθəd ˈsɪɡnɪtʃə/ メソッドシグネチャ
    arguments/ˈɑːɡjuːmənts/ 引数(パラメータ)と呼ばれる
    1.10

    Calling Class Methods

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 static in 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.
    日本語

    学習目標 1.10.A: クラスメソッドを呼び出すコードを作成し、その呼び出しの結果を決定する。

    • 1.10.A.1 クラスメソッド は、クラスのインスタンスではなく、クラス自体に関連付けられる。クラスメソッドのヘッダーには、メソッド名の前に static キーワードが含まれる。
    • 1.10.A.2 クラスメソッドは通常、クラス名とドット演算子を用いて呼び出される。定義されているクラス内でメソッド呼び出しが行われる場合、呼び出しにおいてクラス名を使用することは任意である。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    A class (static) method 类方法 belongs to the class itself, so you call it on the class name: ClassName.method(args). No object is needed.

    日本語

    A class (static) method 类方法 belongs to the class itself, so you call it on the class name: ClassName.method(args). No object is needed.

    Explore · ⁨探索⁩

    Follow a class-method call on the stack

    Calling a class method like Math.max pushes 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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    class (static) method/klæs ˈmeθəd/ クラス(静的)メソッド
    1.11

    Math Class

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential 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 Math class is part of the java.lang package. Classes in the java.lang package are available by default.
    • 1.11.A.2 The Math class contains only class methods. The following Math class 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 an int value.
      • static double abs(double x) returns the absolute value of a double value.
      • 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 a double value.
      • static double random() returns a double value greater than or equal to 0.0 and less than 1.0.
    • 1.11.A.3 The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in 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 · ⁨出典: College Board AP コースおよび試験説明書⁩

    The Math class provides static math methods: Math.abs(x), Math.pow(base, exp), Math.sqrt(x), and Math.random() (a double in $[0,1)$). To get a random integer from 0 to n-1: (int)(Math.random() * n).

    1.12

    Objects: Instances of Classes

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 Object class.

    Learning Objective 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.
    日本語

    学習目標 1.12.A: クラスとオブジェクトの関係について説明する。

    • 1.12.A.1 オブジェクト は、定義された属性を持つ特定のクラスのインスタンスである。クラス は、オブジェクトの属性および振る舞いの形式化された実装、または設計図である。
    • 1.12.A.2 関連するクラスに共通する属性および振る舞いを一つの スーパークラス と呼ばれるクラスにまとめることで、クラス階層を構築できる。スーパークラスを拡張する サブクラス と呼ばれるクラスは、既存の属性および振る舞いに依存でき、これらの属性および振る舞いをコード上で置き換えることはできない。これにより、サブクラスからスーパークラスへの 継承関係 が生まれる。
      • 除外事項: 継承関係の設計および実装は AP Computer Science A コースおよび試験の対象外である。
    • 1.12.A.3 Java のすべてのクラスは Object クラスのサブクラスである。

    学習目標 1.12.B: 引用型を格納するための変数を宣言するコードを作成する。

    • 1.12.B.1 引用型の変数は、オブジェクトへの参照を保持しており、これはそのオブジェクトのメモリアドレスと考えられる。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    = copies the reference, not the object

    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, and ArrayList are all classes you instantiate.

    Classes can be organised into a hierarchy. A superclass 父类 holds attributes and behaviors shared by several subclasses 子类 that extend it – an inheritance relationship 继承关系. Every class in Java is ultimately a subclass of the built-in Object class, which is why every object already has a toString method; writing a subclass method with the same signature as a superclass one is method overriding 方法重写. (Designing your own inheritance is beyond this course, but you are expected to recognise this vocabulary.)

    日本語
    = copies the reference, not the object

    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, and ArrayList are all classes you instantiate.

    Classes can be organised into a hierarchy. A superclass 父类 holds attributes and behaviors shared by several subclasses 子类 that extend it – an inheritance relationship 继承关系. Every class in Java is ultimately a subclass of the built-in Object class, which is why every object already has a toString method; writing a subclass method with the same signature as a superclass one is method overriding 方法重写. (Designing your own inheritance is beyond this course, but you are expected to recognise this vocabulary.)

    A class diagram: private attributes and public methods
    A class diagram: private attributes and public methods
    A class is a blueprint; each object is one instance built from it
    A class is a blueprint; each object is one instance built from it
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    class/klæs/ class
    object/ˈɒbdʒekt/ 物体
    instance/ˈɪnstəns/ インスタンス
    object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ オブジェクト指向プログラミング
    superclass/ˈsuːpəklæs/ スーパークラス
    subclasses/ˈsʌbklæsɪz/ サブクラス
    inheritance relationship/ɪnˈherɪtəns rɪˈleɪʃənʃɪp/ 継承関係
    method overriding/ˈmeθəd ˌəʊvəˈraɪdɪŋ/ メソッドオーバーライド
    1.13

    Object Creation and Storage (Instantiation)

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 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.

    Learning Objective 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 new followed 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.
    日本語

    学習目標 1.13.A: サイグネチャを使用して、正しく呼び出されているコンストラクタを特定する。

    • 1.13.A.1 クラスには、オブジェクトを作成するために呼び出される コンストラクタ が含まれる。それらはクラスと同じ名前を持つ。
    • 1.13.A.2 コンストラクタのサイグネチャ は、コンストラクタの名前(クラス名と同じ)とパラメータタイプの順序付きリストで構成される。ヘッダーにおけるパラメータリストは、渡される値のタイプおよびその変数名を列挙している。
    • 1.13.A.3 サイグネチャが異なる複数のコンストラクタが存在する場合、それらのコンストラクタはオーバーロードされていると言われる。

    学習目標 1.13.B: オブジェクトへの参照を保持する正しい型の変数を宣言するコードを作成する。

    • 1.13.B.1 引用型の変数は、オブジェクトへの参照を保持するか、またはオブジェクトがない場合は null を保持する。

    学習目標 1.13.C: コンストラクタを呼び出してオブジェクトを作成するコードを作成する。

    • 1.13.C.1 オブジェクトは通常、 new キーワードの後に、そのクラスの一つのコンストラクタへの呼び出しが続く形で作成される。
    • 1.13.C.2 パラメータは、コンストラクタが値を受け取り、オブジェクトの属性の初期値を設定することを可能にする。
    • 1.13.C.3 コンストラクタの引数 は、コンストラクタが呼び出された際にコンストラクタへ渡される値である。コンストラクタに渡される引数は、コンストラクタのサイグネチャにおけるパラメータリストで特定されたタイプに対して、順番と数が互いに互換性がある必要がある。コンストラクタを呼び出す際、引数は値による呼び出しによって渡される。値による呼び出しでは、引数のコピーを用いてパラメータが初期化される。
    • 1.13.C.4 コンストラクタの呼び出しは文の直列的な実行を中断させ、プログラムがまずコンストラクタ内の文を実行してから继续する。コンストラクタの最後の文が実行されると、制御の流れはコンストラクタが呼び出された直後の地点に戻される。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    Instantiation 实例化 creates an object with the new keyword, which calls a constructor 构造函数:

    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 reference can also point to nothing: the special value null 空值 means "not attached to any object". Calling a method on a null reference crashes at run time with a NullPointerException. Guard against it by testing with ==/!= and checking null first, so && short-circuits before the method runs: if (s != null && s.length() > 0).

    日本語

    Instantiation 实例化 creates an object with the new keyword, 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 reference can also point to nothing: the special value null 空值 means "not attached to any object". Calling a method on a null reference crashes at run time with a NullPointerException. Guard against it by testing with ==/!= and checking null first, so && short-circuits before the method runs: if (s != null && s.length() > 0).

    A primitive variable holds its value directly, a reference holds an arrow to the object
    A primitive variable holds its value directly, a reference holds an arrow to the object
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Instantiation/ˌɪnstænʃɪˈeɪʃn/ インスタンス化
    constructor/kənˈstrʌktə/ コンストラクタ
    reference/ˈrefrəns/ 基準
    null/nʌl/ null
    1.14

    Calling Instance Methods

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 null reference will result in a NullPointerException.
    日本語

    学習目標 1.14.A: インスタンスメソッドを呼び出し、その呼び出しの結果を決定するコードを作成する。

    • 1.14.A.1 インスタンスメソッド は、そのクラスのオブジェクト上で呼び出される。インスタンスメソッドを呼び出す際、ドット演算子とオブジェクト名が併用される。
    • 1.14.A.2 null への参照に対するメソッド呼び出しは、 NullPointerException を結果として返す。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An instance method 实例方法 acts on a specific object, so you call it on the object reference: object.method(args). Example: in.nextInt(), word.length().

    日本語

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    instance method/ˈɪnstəns ˈmeθəd/ インスタンスメソッド
    1.15

    String Manipulation

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential Knowledge

    1.15.A
    Develop code to create string objects and determine the result of creating and combining strings.

    • 1.15.A.1 A String object represents a sequence of characters and can be created by using a string literal or by calling the String class constructor.
    • 1.15.A.2 The String class is part of the java.lang package. Classes in the java.lang package are available by default.
    • 1.15.A.3 A String object is immutable, meaning once a String object is created, its attributes cannot be changed. Methods called on a String object do not change the content of the String object.
    • 1.15.A.4 Two String objects can be concatenated together or combined using the + or += operator, resulting in a new String object. A primitive value can be concatenated with a String object. This causes the implicit conversion of the primitive value to a String object.
    • 1.15.A.5 A String object can be concatenated with any object, which implicitly calls the object's toString method (a behavior that is guaranteed to exist by the inheritance relationship every class has with the Object class). An object's toString method returns a string value representing the object. Subclasses of Object often override the toString method 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 toString method of a class is outside the scope of the AP Computer Science A course and exam.

    1.15.B
    Develop code to call methods on string objects and determine the result of calling these methods.

    • 1.15.B.1 A String object has index values from 0 to one less than the length of the string. Attempting to access indices outside this range will result in a StringIndexOutOfBoundsException.
    • 1.15.B.2 The following String methods—including what they do and when they are used—are part of the Java Quick Reference:
      • int length() returns the number of characters in a String object.
      • String substring(int from, int to) returns the substring beginning at index from and ending at index to - 1.
      • String substring(int from) returns substring(from, length()).
      • int indexOf(String str) returns the index of the first occurrence of str; returns -1 if not found.
      • boolean equals(Object other) returns true if this corresponds to the same sequence of characters as other; returns false otherwise.
      • int compareTo(String other) returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other. Strings are ordered based upon the alphabet.
      • Exclusion statement: Using the equals method to compare one String object with an object of a type other than String is 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 index can be created by calling substring(index, index + 1).

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Strings are immutable

    String objects are immutable 不可变 – methods return a new string rather than changing the original. Key methods (all indices start at 0):

    Exam skill: substring(a, b) includes index a but excludes b, and String comparison must use .equals, not == – two of the most-tested String pitfalls.

    Worked example. Let String s = "COMPUTER"; (indices 0–7). Then s.length() is 8; s.substring(0, 4) is "COMP" (indices 0,1,2,3 – index 4 excluded); s.substring(4) is "UTER" (from index 4 to the end); s.indexOf("PU") is 3; and s.indexOf("X") is -1 (not found). Counting the excluded endpoint of substring is the single most common slip.

    Asking for an index outside 0 to length()-1 (a bad substring or charAt argument, e.g. s.substring(0, 20) here) crashes with a StringIndexOutOfBoundsException – the String cousin of the array-index error.

    日本語
    Strings are immutable

    String objects are immutable 不可变 – methods return a new string rather than changing the original. Key methods (all indices start at 0):

    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 order
    

    Exam skill: substring(a, b) includes index a but excludes b, and String comparison must use .equals, not == – two of the most-tested String pitfalls.

    Worked example. Let String s = "COMPUTER"; (indices 0–7). Then s.length() is 8; s.substring(0, 4) is "COMP" (indices 0,1,2,3 – index 4 excluded); s.substring(4) is "UTER" (from index 4 to the end); s.indexOf("PU") is 3; and s.indexOf("X") is -1 (not found). Counting the excluded endpoint of substring is the single most common slip.

    Asking for an index outside 0 to length()-1 (a bad substring or charAt argument, e.g. s.substring(0, 20) here) crashes with a StringIndexOutOfBoundsException – the String cousin of the array-index error.

    String indices start at 0
    String indices start at 0
    Explore · ⁨探索⁩

    Explore 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 from from up to — but not including — to.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    immutable/ɪˈmjuːtəbl/ 不変
    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 – know the named ones: ArithmeticException (int ÷ 0), NullPointerException (method on a null reference), StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException – 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 · ⁨選択と反復⁩

    Watch lesson · ⁨レッスンを視聴⁩
    2.1

    Selection and Repetition in Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 2.1.A: 日常生活で見られる選択と反復を含むパターンやアルゴリズムを、言語表記や図で表現する。

    • 2.1.A.1 アルゴリズムの構成要素には、順次処理、選択、反復が含まれる。
    • 2.1.A.2 アルゴリズムには、意思決定による選択、およびループによる反復が含まれ得る。
    • 2.1.A.3 選択 とは、アルゴリズムの実行経路如何选择するかの判断が真偽値に基づいて行われることを指す。
    • 2.1.A.4 反復 (Repetition) とは、所望の結果が得られるまでプロセスが繰り返されることである。
    • 2.1.A.5 順次処理、選択、反復の使用順序は、アルゴリズムの結果に影響を与える。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語
    A flowchart with a decision diamond: selection chooses which path the algorithm takes
    A flowchart with a decision diamond: selection chooses which path the algorithm takes

    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 iteration
    The three control structures: sequence, selection, and iteration
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    control structures/kənˈtrəʊl ˈstrʌktʃəz/ 制御構造
    selection/sɪˈlekʃn/ 選択
    iteration/ˌɪtəˈreɪʃn/ 反復処理
    2.2

    Boolean Expressions

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標2.2.A: 関係演算子を用いてブール式を作成するコードを作成し、これらの式の結果を決定する。

    • 2.2.A.1 値は、関係演算子 == および != を用いて比較され、値が等しいかどうかを判定できる。プリミティブ型の場合、これは実際のプリミティブ値を比較する。参照型の場合、これはオブジェクトの参照を比較する。
    • 2.2.A.2 数値値は、関係演算子 <、>、<=、および >= を用いて比較され、値間の関係を判定できる。
    • 2.2.A.3 関係演算子を含む式は、ブール値に評価される。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Logic gates & the half-adder

    A boolean expression 布尔表达式 evaluates to true or false, using relational operators 关系运算符: == (equal), != (not equal), <, >, <=, >=. Note == compares primitive values but object references for objects, so use .equals for Strings.

    日本語
    Logic gates & the half-adder

    A boolean expression 布尔表达式 evaluates to true or false, using relational operators 关系运算符: == (equal), != (not equal), <, >, <=, >=. Note == compares primitive values but object references for objects, so use .equals for Strings.

    The three families of operators: arithmetic, relational, and logical
    The three families of operators: arithmetic, relational, and logical
    Explore · ⁨探索⁩

    Explore the AND truth table · ⁨ANDの真理表を確認する⁩

    A Boolean expression evaluates to true or false. AND is true only when both operands are true; toggle the inputs to see all four cases. · ⁨**布尔表达式(布尔表达式)**はtrueまたはfalseに評価されます。AND演算子は両方の操作数が真の場合にのみ真となります。入力を切り替えてすべての4つのケースを確認してください。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    boolean expression/ˈbuːlɪən ekˈspreʃn/ ブール式
    relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/ 関係演算子
    2.3

    The if Statement

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 if statement 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 (if statement) 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 is true.
    • 2.3.A.4 A two-way selection (if-else statement) is used when there are two segments of code—one to be executed when the Boolean expression is true and another segment for when the Boolean expression is false. In this case, the body of the if is executed when the Boolean expression is true, and the body of the else is executed when the Boolean expression is false.
    日本語

    学習目標2.3.A: 選択文を用いて分岐論理プロセスを表現するコードを作成し、これらのプロセスの結果を決定する。

    • 2.3.A.1 選択文は、文の順次実行を変更する。
    • 2.3.A.2 if 文は、選択文の一種であり、ブール式の値に基づいて異なるコードセグメントを実行することで制御の流れに影響を与える。
    • 2.3.A.3 単方向選択(if 文)は、特定の条件下で実行すべきコードセグメントがある場合に使用される。この場合、本体はブール式が true のときのみ実行される。
    • 2.3.A.4 二重選択 (two-way selection) (if-else 文)は、布尔表达式 (Boolean expression) が true のときに実行されるコードセグメントと、布尔表达式 が false のときに実行される別のコードセグメントがある場合に使用される。この場合、if の本体は布尔表达式 が true のときに実行され、else の本体は布尔表达式 が false のときに実行される。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An if statement 条件语句 runs a block only when its condition is true; an optional else gives an alternative:

    日本語

    An if statement 条件语句 runs a block only when its condition is true; an optional else gives an alternative:

    if (score >= 60) {
        System.out.println("Pass");
    } else {
        System.out.println("Fail");
    }
    
    Traffic lights: selection chooses which branch runs, just as if statements choose code paths
    Traffic lights: selection chooses which branch runs, just as if statements choose code paths
    Explore · ⁨探索⁩

    See which branch an if chooses · ⁨if文がどの分岐を選択するか確認する⁩

    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. · ⁨if文は条件が真のときにその本体を実行し、それ以外の場合はelseへスキップします。スコアを境界線間スライドさせて、成績がどのように変化するか観察してください。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    if statement/ɪf ˈsteɪtmənt/ if文
    2.4

    Nested if Statements

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential Knowledge

    2.4.A
    Develop code to represent nested branching logical processes and determine the result of these processes.

    • 2.4.A.1 Nested if statements consist of if, if-else, or if-else-if statements within if, if-else, or if-else-if statements.
    • 2.4.A.2 The Boolean expression of the inner nested if statement is evaluated only if the Boolean expression of the outer if statement evaluates to true.
    • 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 to true. If no expression evaluates to true and there is a trailing else statement, then the body of the else is executed.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    Placing an if inside another, or chaining with else 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 ObjectiveEssential 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 !a evaluates to true if a is false and evaluates to false otherwise. The expression a && b evaluates to true if both a and b are true and evaluates to false otherwise. The expression a || b evaluates to true if a is true, b is true, or both, and evaluates to false otherwise. 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 · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Short-circuit evaluation

    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).

    日本語
    Short-circuit evaluation

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/ 論理演算子
    short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/ 短路評価
    2.6

    Comparing Boolean Expressions

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 || !b and the Boolean expression !(a || b) is equivalent to !a && !b.

    Learning Objective 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 equals method, 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 equals method is outside the scope of the AP Computer Science A course and exam.
    日本語

    学習目標2.6.A: 同等のブール式を比較する。

    • 2.6.A.1 2つのブール式は、同等である。すべての場合において同じ値に評価される場合である。真値表を使用して、ブール式が同等であることを証明できる。
    • 2.6.A.2 ド・モルガンの法則をブール式に適用して同等のブール式を作成できる。ド・モルガンの法則により、ブール式 !(a && b) は !a || !b と同等であり、ブール式 !(a || b) は !a && !b と同等である。

    学習目標2.6.B: 参照型オブジェクトの参照をブール式で比較するコードを作成し、これらの式の結果を決定する。

    • 2.6.B.1 2つの異なる変数が同一のオブジェクトへの参照を保持することがある。オブジェクトの参照は、== と != を用いて比較できる。
    • 2.6.B.2 オブジェクトの参照は、null で、== または != を用いて比較され、その参照が実際にオブジェクトを指しているかどうかを判定できる。
    • 2.6.B.3 クラスは通常、独自の equals メソッドを定義しており、これ使用该用于指定该类两个对象的等价性标准。两个对象的等价性最常通过这两个对象的属性来确定。
      • 除外文: equals メソッドのオーバーライドはAPコンピュータサイエンスAコースおよび試験の対象外です。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    De Morgan's laws/də ˈmɔːɡənz lɔːz/ ド・モーガンの法則
    2.7

    while Loops

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 2.7.B: Develop code to represent iterative processes using while loops and determine the result of these processes.

    • 2.7.B.1 A while loop is a type of iterative statement. In while loops, the Boolean expression is evaluated before each iteration of the loop body, including the first. When the expression evaluates to true, the loop body is executed. This continues until the Boolean expression evaluates to false, whereupon the iteration terminates.
    日本語

    学習目標 2.7.A: 所望の結果を得るために反復処理が必要となるタイミングを特定する。

    • 2.7.A.1 反復 は繰り返しの一種である。反復文は、ループを制御するブール式が true に評価される限り、コードのセグメントをゼロ回以上繰り返し実行することで制御の流れを変更する。
    • 2.7.A.2 無限ループ は、反復文内のブール式が常に true に評価される場合に発生する。
    • 2.7.A.3 反復文のループ本体は、ブール式が最初に false に評価されない場合、実行されない。
    • 2.7.A.4 Off by one エラーとは、反復文が一度多すぎるか少なさすぎたりしてループが実行されるエラーのことである。

    学習目標 2.7.B: while ループを使用して反復処理を表すコードを作成し、これらの処理の結果を決定する。

    • 2.7.B.1 while ループは反復文の一種である。while ループでは、ループ本体の最初の反復を含む各反復の前にブール式が評価される。式が true に評価されればループ本体が実行される。このプロセスは、ブール式が false に評価されるまで続き、その時点で反復は終了する。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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 无限循环:

    日本語

    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 tested
    The three loop types differ in where the condition is tested
    int i = 0;
    while (i < 5) {
        System.out.println(i);
        i++;
    }
    
    Explore · ⁨探索⁩

    Trace a while loop · ⁨whileループを追跡する⁩

    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. · ⁨whileループは条件が真である限り繰り返し、各反復ごとに変数を更新します。ステップ実行して、二乗和がどのように蓄積されていくか確認してください。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    while loop/waɪl luːp/ whileループ
    infinite loop/ˈɪnfɪnət luːp/ 無限ループ
    2.8

    for Loops

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 2.8.A: Develop code to represent iterative processes using for loops and determine the result of these processes.

    • 2.8.A.1 A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
    • 2.8.A.2 In a for loop, 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 is false. 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 for loop can be rewritten into an equivalent while loop (and vice versa).
    日本語

    学習目標 2.8.A: for ループを使用して反復処理を表すコードを作成し、これらの処理の結果を決定する。

    • 2.8.A.1 for ループは反復文の一種である。for ループのヘッダーには3つの部分がある:初期化、ブール式、および更新(更新式)。
    • 2.8.A.2 for ループでは、初期化文は最初のブール式評価の前に行われ、一度だけ実行されます。初期化される変数はループ制御変数と呼ばれます。ブール式はループ制御変数が初期化された直後、および増分文が実行されるたびに評価され、false になるまで続きます。各反復において、更新はループ本体全体の実行後、ブール式の再評価前に実行されます。
    • 2.8.A.3 for ループは同等の while ループに書き換えられ(逆もまた真)、その逆も可能である。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    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 for and an equivalent while do the same work; be able to convert between them.

    An assembly line: loops repeat a process for every item, like for and while
    An assembly line: loops repeat a process for every item, like for and while
    Explore · ⁨探索⁩

    Trace a for loop · ⁨forループを追跡する⁩

    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. · ⁨forループは固定回数実行され、カウントが範囲を順にたどります。カウントと累積合計が1反復ずつ進行する様子を観察してください。⁩

    2.9

    Building Complete Selection and Iteration Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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
    日本語

    学習目標 2.9.A: データ構造を使用しない標準的かつ独自のアルゴリズムのコードを作成し、これらのアルゴリズムの結果を決定する。

    • 2.9.A.1 以下のための標準的なアルゴリズムが存在する:
      • 整数が他の整数によって均等に割り切れるかどうかを特定する
      • 整数を構成する個々の桁を特定する
      • 特定の基準が満たされる頻度を決定する
      • 最小値または最大値を決定する
      • 合計や平均を計算する

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    Combine loops and conditions to solve real problems – count, sum, find a maximum, or test a property:

    Two integer patterns the exam tests directly use % and /. To read the digits of an integer one at a time, repeatedly take n % 10 (the last digit) and then n = n / 10 (drop it). To test divisibility, n % d == 0 means n is evenly divisible by d. Combine them with a counter to find the frequency with which some criterion is met.

    Standard patterns like a running total, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.

    日本語

    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];
    }
    

    Two integer patterns the exam tests directly use % and /. To read the digits of an integer one at a time, repeatedly take n % 10 (the last digit) and then n = n / 10 (drop it). To test divisibility, n % d == 0 means n is evenly divisible by d. Combine them with a counter to find the frequency with which some criterion is met.

    Standard patterns like a running total, a counter, or a flag 标志 (a boolean that records whether something happened) recur throughout the course.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    flag/flæɡ/ フラグ
    2.10

    String Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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
    日本語

    学習目標 2.10.A: ストリングを含む標準的および独自のアルゴリズムのコードを作成し、これらのアルゴリズムの結果を決定する。

    • 2.10.A.1 標準的なストリング・アルゴリズムには以下が含まれる:
      • 1つ以上の部分文字列が特定の性質を持つかを確認する
      • 特定の基準を満たす部分文字列の個数を決定する
      • 文字の順序を逆にした新しいストリングを作成する

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    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 · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標2.11.A: 重複反復プロセスを表現するコードを作成し、これらのプロセスの結果を決定する。

    • 2.11.A.1 重複反復文は、別の反復文の本体に配置された反復文である。ループが他のループ内に配置される場合、内側のループがすべての反復を完了するまで、外側のループは次の反復に進むことができない。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    nested loop/ˈnestɪd luːp/ ネストループ
    2.12

    Informal Run-Time Analysis

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標2.12.A: 文の実行回数を計算し、反復文の非形式的な実行時間を比較する。

    • 2.12.A.1 文の実行回数とは、プログラムによって文が実行される回数を示す。文の実行回数は、反復文のトレースと分析を通じて非形式的に計算されることが多い。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Big-O growth rates

    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.

    Exam 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?

    The inner loop runs i times for each outer i: 0 + 1 + 2 + 3 = 6 stars. 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.

    日本語
    Big-O growth rates

    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 n
    How the running time grows with the number of elements n

    Exam 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 i times for each outer i: 0 + 1 + 2 + 3 = 6 stars. 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.

    Explore · ⁨探索⁩

    Compare 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)$. · ⁨実行時間は、入力サイズ$n$に対するステップ数の増加数を説明します。$n$を増やすと、線形の$O(n)$が二次の$O(n^2)$を大きく引き離す様子が確認できます。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Run-time analysis/rʌn taɪm əˈnæləsɪs/ 実行時解析
    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 if for 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 · ⁨クラス定義⁩

    Watch lesson · ⁨レッスンを視聴⁩
    3.1

    Abstraction and Program Design · ⁨アブストラクションとプログラム設計⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 3.1.A: 自然言語を使用するか、クラス図を作成することでプログラムの設計を表現する。図には、各クラスに含まれるデータおよび手続的抽象化(すべての属性と振る舞いを含む)を示す必要がある。

    • 3.1.A.1 抽象化 は、主要な概念に焦点を当てることで複雑さを軽減するプロセスである。現在の質問に関連しない詳細を隠し、関連して有用な詳細をまとめすることで、抽象化は複雑さを軽減し、概念への集中を可能にする。
    • 3.1.A.2 データ抽象化 は、データ型の抽象的特性とその表現の具体的な詳細との間に区別を提供する。データ抽象化は、表現の具体的な詳細を参照せずにデータに名前を与えることで複雑さを管理する。データは単一の変数として、またはクラスやデータセットなどのデータの集合体として存在する。
    • 3.1.A.3 属性 は、メソッドやコンストラクタの外でクラス内に定義されるデータ抽象化の一種である。インスタンス変数 は、クラスの各インスタンスごとに値が固有である属性である。クラス変数 は、クラスの全インスタンスで共有される属性である。
    • 3.1.A.4 手続的抽象化 はプロセスに名前を与え、メソッドがどのように動作するかではなく何をするのかを知っているだけで使用できるようにする。メソッド分解 を通じて、プログラマーはクラスにより大きな振る舞いをより小さな振る舞いに分解し、それぞれの小さな振る舞いを表すメソッドを作成する。手続的抽象化は、コードを複製する代わりに共通要素を抽出して機能を一般化することがある。これによりコード再利用が可能になり、複雑性の管理に役立つ。
    • 3.1.A.5 パラメータを使用することでプロシージャを一般化でき、異なる入力値や引数を用いてプロシージャを再利用できる。
    • 3.1.A.6 プログラム内で手続的抽象化を使用することで、メソッドの署名とメソッドが何をするかを維持している限り、メソッドユーザーに変更を通知することなく、メソッドの内部(速度向上、効率化、メモリ使用量の削減など)を変更できる。
    • 3.1.A.7 クラスを実装する前に、各クラスの属性と振る舞いを含めた設計に時間を割くことが有益である。この設計は自然言語や図で表現できる。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    Abstraction 抽象 means hiding detail behind a simple interface – you use a String without 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.

    日本語
    進行中のジigsawパズル: クラスとメソッドは大きなプログラム設計におけるモジュール単位のピースです
    進行中のジigsawパズル: クラスとメソッドは大きなプログラム設計におけるモジュール単位のピースです

    抽象化とは、単純なインターフェースの背後に詳細を隠すことを意味します。Stringを使用する際、それがどのように文字を格納しているかを知る必要はありません。良い設計では問題をクラスに分解し、各クラスが一つの概念について責任を持ちます。このトピックでは、あなた自身がクラスを書くことについて扱います。

    プログラムをモジュールとサブモジュールに分解した様子
    プログラムをモジュールとサブモジュールに分解する
    3.2

    The Impact of Program Design · ⁨プログラム設計の影響⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 3.2.A: コンピューティングシステムの社会的・倫理的 implications を説明する。

    • 3.2.A.1 システム信頼性 とは、指定された条件下で故障なく予期したタスクを遂行できるプログラムの能力を指す。プログラマーは、多様な条件下でプログラム进行测试してシステム信頼性を最大化するよう努めるべきである。
    • 3.2.A.2 プログラムの作成は、社会、経済、文化に影響を与えます。これらの影響には、利益となるものと害をなすものとの両方が含まれます。特定のニーズを満たしたり問題を解決したりするために設計されたプログラムでも、その意図した用途を超えて予期せぬ有害な効果が生じることがあります。
    • 3.2.A.3 プログラムを作成する際、法的問題や知的財産に関する懸念が生じます。プログラマはしばしば、他の人が作成してオープンソースとして公開し無料で利用可能なコードを再利用します。オープンソースとして公開されていないコードを取り込む場合、プログラマはその使用許諾を取得し、統合する前に多くの場合、コードを購入する必要があります。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    Design also carries responsibility beyond the code. System reliability 系统可靠性 - a program performing its tasks as expected, without failure - is something programmers should maximise through careful design and testing. Programs have real impacts on society, the economy, and culture that can be both beneficial and harmful. And creating programs raises legal and intellectual-property 知识产权 concerns: programmers often reuse code published as open source 开源 and free to use, but must respect its licence and give credit rather than copy others' work as their own.

    日本語

    設計上の選択は、コードが正しいか、読みやすいか、再利用可能かどうかに影響します。カプセル化 – データをプライベートに保ち、メソ要通过のみで公開する – はオブジェクトの状態を誤った使用から守り、内部を変更してもクラスのユーザーを破綻させません。 thoughtfulなネーミング、単一目的のメソッド、テストによりバグが減ります。

    設計はコード以上の責任も伴います。システム信頼性 – 予期通りタスクを遂行し、失敗なしのプログラム – は、慎重な設計とテストを通じてprogrammableが最大化すべきものです。プログラムは社会、経済、文化に有益かつ有害の両方の現実的な影響を与えます。また、プログラムの作成は法的および知的財産の問題を提起します – programmersはよくオープンソースとして公開され無料で使えるコードを再利用しますが、ライセンスを尊重し、他者の作品をそのまま自分のものとしてコピーするのではなく、出典を示す必要があります。

    3.3

    The Anatomy of a Class · ⁨クラスの解剖学⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.
    • 3.3.A.2 In this course, classes are always designated public and are declared with the keyword class.
    • 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 private unless the class specification states otherwise.
    • 3.3.A.6 Access to behaviors can be internal or external to the class. Methods designated as public can be accessed internally or externally to a class, whereas methods designated as private can only be accessed internally to the class.
    日本語

    学習目標 3.3.A: クラス、データ、コンストラクタ、およびメソッドに対するアクセスと可視性制約を指定するコードを作成する。

    • 3.3.A.1 データカプセル化とは、クラスの実装詳細を外部のクラスから隠蔽する技術である。キーワード public と private は、クラス、データ、コンストラクタ、およびメソッドへのアクセスに影響を与える。キーワード private は宣言クラス内でのみアクセスを制限し、キーワード public は宣言クラス以外のクラスからのアクセスを許可する。
    • 3.3.A.2 このコースでは、クラスは常に public として指定され、キーワード class を用いて宣言される。
    • 3.3.A.3 このコースでは、コンストラクタは常に public として指定される。
    • 3.3.A.4 インスタンス変数 はオブジェクトに属し、各オブジェクトはその変数の独自のコピーを持つ。
    • 3.3.A.5 カプセル化を実現するため、属性へのアクセスはクラス内部に留めるべきである。したがって、クラス仕様で別に定められていない限り、これらの属性に対応するインスタンス変数を private として指定することが良いプログラミング慣行である。
    • 3.3.A.6 ビヘイビア(振る舞い)へのアクセスは、クラス内部または外部のいずれか可以是である。 public として指定されたメソッドは、クラス内部および外部の両方からアクセス可能であるが、 private として指定されたメソッドはクラス内部のみからアクセス可能である。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    A class has three parts: instance variables 实例变量 (fields – the object's data), constructors (build objects), and methods (behavior). Fields are usually private; methods are usually public:

    日本語

    クラスには三つの部分があります:インスタンス変数(フィールド – オブジェクトのデータ)、コンストラクタ(オブジェクトの生成)、そしてメソッド(振る舞い)。フィールドは通常 private で、メソッドは通常 public です:

    クラス図: プライベート属性とパブリックメソッド
    クラス図: プライベート属性とパブリックメソッド
    public 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
    }
    
    青写真: クラスはその型のオブジェクトがどのように構築されるかを定義するテンプレートです
    青写真: クラスはその型のオブジェクトがどのように構築されるかを定義するテンプレートです
    Explore · ⁨探索⁩

    See 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. · ⁨クラスは関連するデータ(fields)とメソッドをグループ化します。各オブジェクトには独自のフィールドボックスのセットが割り当てられ、1つに代入しても対象となるオブジェクトのみが変化します。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Abstraction/əbˈstrækʃn/ 抽象化
    Encapsulation/ɪnˌkæpsjʊˈleɪʃn/ カプセル化
    System reliability/ˈsɪstəm rɪˌlaɪəˈbɪlɪti/ システム信頼性
    legal and intellectual-property/ˈliːɡl ænd ˌɪntəˈlektʃuːəl ˈprɒpəti/ 法的および知的財産権
    open source/ˈəʊpən sɔːs/ オープンソース
    instance variables/ˈɪnstəns ˈveərɪəblz/ インスタンス変数
    constructor/kənˈstrʌktə/ コンストラクタ
    overloading/ˌəʊvəˈləʊdɪŋ/ オーバーロード
    accessor (getter)/əkˈsesə/ アクセサ(ゲッター)
    3.4

    Constructors · ⁨コンストラクタ⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 int is 0. The default value of an attribute of type double is 0.0. The default value of an attribute of type boolean is false. The default value of a reference type is null.
    日本語

    学習目標 3.4.A: クラスのコンストラクタ本体において初期化する対象の属性に対応するインスタンス変数を宣言するコードを作成する。

    • 3.4.A.1 オブジェクトの 状態 は、ある時点におけるその属性およびその値を指し、オブジェクトに属するインスタンス変数によって定義される。これは、オブジェクトとインスタンス変数の間に has-a 関係が成立することを意味する。
    • 3.4.A.2 コンストラクタは、オブジェクトの初期状態を設定するために用いられ、すべてのインスタンス変数に対する初期値を含めるべきである。コンストラクタが呼び出されると、オブジェクトのためにメモリが割り当てられ、関連するオブジェクト参照が返される。コンストラクタのパラメータ(指定されている場合)は、インスタンス変数を初期化するためのデータを提供する。
    • 3.4.A.3 可変オブジェクトがコンストラクタパラメータである場合、インスタンス変数は参照先のオブジェクトのコピーで初期化されるべきである。このようにすることで、インスタンス変数は元のオブジェクトへの参照を持たず、メソッドによる元のオブジェクトの状態の変更を防ぐことができる。
    • 3.4.A.4 コンストラクタが書かれていない場合、Javaは引数なしのコンストラクタを提供し、インスタンス変数は属性のデータ型に応じてデフォルト値に設定される。このコンストラクタを デフォルトコンストラクタ と呼ぶ。
    • 3.4.A.5 int 型の属性のデフォルト値は 0 である。 double 型の属性のデフォルト値は 0.0 である。 boolean 型の属性のデフォルト値は false である。参照型の変数のデフォルト値は null である。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語

    コンストラクタはクラスと同じ名前を持ち、返り値の型はありません。new を書いたときに実行され、フィールドを初期化する役割があります。パラメータリストが異なる複数のコンストラクタ(オーバーロード)を持つことができ、引数なしのコンストラクタはデフォルト値を設定します。

    3.5

    Methods: How to Write Them · ⁨メソッド: 書き方⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 void method does not return a value. Its header contains the keyword void before 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 return keyword 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.
    日本語

    学習目標 3.5.A: プリミティブ値を用いてクラス内に書かれたメソッドを通じてオブジェクトの振る舞いを定義するコードを作成し、これらのメソッドを呼び出した結果を判定する。

    • 3.5.A.1 void メソッドは値を返さない。そのヘッダーには、メソッド名の前にキーワード void が含まれる。
    • 3.5.A.2 非voidメソッドは単一の値を返す。そのヘッダーには、キーワード void の代わりに返り値の型が含まれる。
    • 3.5.A.3 非voidメソッドでは、返り値の型と互換性のある返還式が評価され、その値が返される。これを 値による返還 と呼ぶ。
    • 3.5.A.4 return キーワードは、制御の流れをメソッドまたはコンストラクタが呼び出された地点へ戻すために用いられる。return文の後に続くコードは決して実行されない。選択文または反復文内でreturn文を実行すると、该文が停止し、メソッドまたはコンストラクタから退出する。
    • 3.5.A.5 アクセサメソッド は、他のクラスのオブジェクトがインスタンス変数またはクラス変数の値のコピーを取得できるようにするメソッドである。アクセサメソッドは非voidメソッドである。
    • 3.5.A.6 ミューテータ(修飾)メソッド は、インスタンス変数またはクラス変数の値を変更するメソッドである。ミューテータメソッドは多くの場合、voidメソッドである。
    • 3.5.A.7 パラメータを持つメソッドは、そのパラメータを通じて値を受け取り、その値を使用してメソッドのタスクを遂行する。
    • 3.5.A.8 引数がプリミティブ値である場合、パラメータはその値のコピーで初期化される。パラメータへの変更は対応する引数には影響しない。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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 return of the right type on every path; a void method returns nothing.

    日本語

    メソッドにはシグネチャ、返り値の型、本体があります。アクセサ(ゲッター) はオブジェクトを変更することなく情報を返します。ミューテータ(セッター) はフィールドを変更します。値を返すメソッドは、すべてのパスで適切な型のreturnを持つ必要があります;voidメソッドは何も返しません。

    public void setScore(int s) { score = s; }   // mutator
    public String toString() { return name + ": " + score; }
    
    Explore · ⁨探索⁩

    Follow 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. · ⁨メソッドを呼び出すと、その引数を含むフレームがスタックに押し込まれます。returnに到達するとフレームがポップされ、値が呼び出し元に戻ります。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    mutator (setter)/mjuːˈteɪtə/ ミューテータ(セッター)
    static (class) variable/ˈstætɪk ˈveərɪəbl/ 静的(クラス)変数
    3.6

    Passing and Returning References of an Object · ⁨オブジェクトへの参照の渡還と返却⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 3.6.A: オブジェクト参照を用いてクラス内に書かれたメソッドを通じてオブジェクトの振る舞いを定義するコードを作成し、これらのメソッドを呼び出した結果を判定する。

    • 3.6.A.1 引数がオブジェクト参照である場合、パラメータはその参照のコピーで初期化されますが、オブジェクト自体の新しい独立したコピーは作成されません。パラメータが可変なオブジェクトを指している場合、メソッドやコンストラクタはこの参照を使ってオブジェクトの状態を変更できます。仕様で必要とされない限り、パラメータとして渡された可変なオブジェクトを修改しないことが良いプログラミングの慣行です。
    • 3.6.A.2 返り値がオブジェクト参照を評価する場合、その参照が返されますが、オブジェクトの新しいコピーに対する参照が返されるわけではありません。
    • 3.6.A.3 パラメータがオブジェクトへの参照を持っている場合、そのパラメータがメソッドを包み込むクラスと同じ型でない限り、メソードはパラメータの private データや private メソッドにアクセスできません。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    = copies the reference, not the object

    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 String is immutable, passing one is safe; passing a mutable object lets a method change it.

    Exam 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 s is a Student with score 50, and we call tweak(s):

    Line (1) changes the object s points to, so the caller now sees 100. Line (2) makes the method's own copy of the reference point at a fresh object – the caller's s is untouched – and line (3) affects only that new object. After the call, s.getScore() is 100: the mutation stuck, the reassignment did not.

    日本語
    = はオブジェクトそのものをコピーするのではなく参照をコピーします

    オブジェクトをメソッドに渡すと、Javaは参照のコピーを取るため、メソッドは同じオブジェクトに対して動作し、そのフィールドへの変更は呼び出し主に visibility されます。(プリミティブは値によってコピーされるため、変更は反映されません。)メソッドはまた、オブジェクトへの参照を返すこともできます。String は不変体であるため、渡すことは安全ですが、可変なオブジェクトを渡すとメソッドが変更できます。

    Javaは値渡し:メソッドはコピーを受け取ります。Javaには欠如している真の参照渡しであれば、呼び出し者の変数を再代入できます *Javaは常に値渡し(左):メソッドは参照のコピーを取得する。真の参照渡し(右)– Javaにはない – は、メソッドが呼び出し主自身の変数を再割り当てすることを可能にする。

    試験技能: メソッド内でオブジェクトのフィールドを改変すると元の値に影響を与えるが、パラメータの再割り当て(param = new...)は呼び出し主に影響しないことを知っておく。

    演習例。 sがStudentであり、得点が50であると仮定して、tweak(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
    }
    

    行(1)はs が指すオブジェクトを変更するため、呼び出し主は now 100 を見る。行(2)はメソッド自身の参照のコピーを新しいオブジェクトにポイントさせる – 呼び出し主の s は untouched – 、行(3)はその新しいオブジェクトのみに影響する。呼び出し後、s.getScore() は 100 である:mutationは残ったが、reassignmentは残らなかった。

    3.7

    Class Variables and Class Methods · ⁨クラス変数とクラスメソッド⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 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 static keyword before the variable type.
    • 3.7.B.2 Class variables that are designated public are 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.
    日本語

    学習目標 3.7.A: クラスメソッドを通じてクラスの振る舞いを定義するコードを作成する。

    • 3.7.A.1 クラスメソッドは、パラメータ経由でクラスのインスタンスが渡されていない限り、インスタンス変数の値にアクセスしたり変更したり、インスタンスメソッドを呼び出したりすることはできません。
    • 3.7.A.2 クラスメソッドはクラス変数の値にアクセスしたり変更したりでき、他のクラスメソッドを呼び出すことができます。

    学習目標 3.7.B: クラスに属するクラス変数を宣言するコードを作成する。

    • 3.7.B.1 クラス変数はクラスに属し、あるクラスのすべてのオブジェクトがそのクラス変数の単一のコピーを共有します。クラス変数は変数名の前に static キーワードが付与されます。
    • 3.7.B.2 public で指定されたクラス変数は、クラスに紐付いているため、クラスのオブジェクトではなく、クラス名とドット演算子を使用してクラス外からアクセスされます。
    • 3.7.B.3 変数が final で宣言された場合、その値は修改できません。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    static vs instance fields

    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().

    日本語

    *static vs インスタンスフィールド

    static(クラス)変数は static でマークされており、クラスの全オブジェクトで共有される – 全体で一つのコピー(例:存在するオブジェクトのカウンター)。staticメソッドはクラスに属し、インスタンスフィールドを直接使うことはできません。クラス名でアクセスする:Student.getCount()。

    3.8

    Scope and Access · ⁨スコープとアクセス⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 public or private.
    • 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.
    日本語

    学習目標 3.8.A: コード内で変数がどこで使用できるかを説明する。

    • 3.8.A.1 ローカル変数 は、コードブロックのヘッダーまたは本体に宣言された変数です。ローカル変数は、宣言されたブロック内でのみアクセスできます。コンストラクタとメソッドはコードブロックであるため、コンストラクタやメソッドのパラメータもローカル変数とみなされます。これらの変数はコンストラクタやメソッド内でのみ使用でき、public や private に宣言することはできません。
    • 3.8.A.2 インスタンス変数と同じ名前のローカル変数やパラメータが存在する場合、コンストラクタやメソッドの本体では変数名はインスタンス変数ではなくローカル変数を指します。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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) versus public (anywhere). Local variables shadow fields of the same name – a source of bugs.

    日本語

    スコープとは、名前が visibility される場所である。メソッド内で宣言されたローカル変数はその中にのみ存在し、パラメータはそのメソッド内にのみ存在し、インスタンス変数はオブジェクト全体で visibility される。アクセス修飾子はクラス間での visibility を制御する:private(このクラスのみ)対 public(どこでも)。ローカル変数は同名のフィールドをシャドウイングする – バグの原因になる。

    グローバル変数はどこでも visibility される; ローカル変数はブロック内でのみ visibility される
    グローバル変数はどこでも visibility される; ローカル変数はブロック内でのみ visibility される
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Scope/skəʊp/ スコープ
    3.9

    The this Keyword · ⁨this キーワード⁩

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 this acts 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 this can be used to pass the current object as an argument in a method call.
    • 3.9.A.3 Class methods do not have a this reference.
    日本語

    学習目標 3.9.A: 自身を参照する式のためのコードを作成し、これらの式の結果を決定する。

    • 3.9.A.1 インスタンスメソッドやコンストラクタ内で、キーワード this は現在のオブジェクトへの参照を持つ特殊な変数として機能します。これは、現在メソッドやコンストラクタが呼び出されているオブジェクトです。
    • 3.9.A.2 キーワード this を使用して、現在のオブジェクトをメソッド呼び出しの引数として渡すことができます。
    • 3.9.A.3 クラスメソッドには this 参照がありません。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    this is 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:

    Exam skill: when a constructor or setter's parameter has the same name as a field, you must write this.field = param – without this, the assignment does nothing useful.

    日本語

    this は現在のオブジェクトを指します。同じ名前のパラメータと区別したり、同じオブジェクトの他のメソッドを呼び出したりするために使用します:

    public Student(String name, int score) {
        this.name = name;      // this.name is the field; name is the parameter
        this.score = score;
    }
    

    試験対策: コンストラクタやセットメソッドのパラメータがフィールドと同じ名前の場合、this.field = param を必ず書く必要があります——this がなければ、代入は意味のある動作を行いません。

    3.9

    Exam tips · ⁨試験対策⁩

    English
    • Design with methods and classes: encapsulate data as private fields and expose behaviour through public methods.
    • Know the difference between an object and its class, and that objects are passed by value — the parameter gets a copy of the reference, so a method can change the object's state, but reassigning the parameter does not affect the caller (Java has no pass-by-reference).
    • Traverse arrays and ArrayLists safely — size is length vs .size(), and removing during a loop shifts indices.
    • Trace a recursive method to determine its result: find the base case first, then follow each recursive call to its return value (writing recursive code is outside the exam's scope).
    • Recognise inheritance vocabulary — superclass, subclass, method overriding, and that every class is a subclass of Object (designing and implementing inheritance is outside the exam's scope).
    日本語
    • メソッドとクラスを用いた設計:データをprivate フィールドとしてカプセル化し、公的メソッドを通じて振る舞いを公開する。
    • オブジェクトとそれに対応するクラスの違いを理解し、オブジェクトは値渡しで渡されることを知る——パラメータには参照のコピーが入るため、メソッド内でオブジェクトの状態を変更することはできるが、パラメータへの再割り当ては呼び出し側に影響しない(Javaには参照渡しはない)。
    • アレイとArrayList を安全にトラバースする——サイズはlength と.size() で異なり、ループ中に要素を削除するとインデックスがシフトする。
    • 再帰メソッドをトレースして結果を求める:まず基底ケースを見つけ、次に各再帰呼び出しが返す値まで追跡する(再帰コードの記述は試験範囲外)。
    • 継承に関する用語を理解する——スーパークラス、サブクラス、メソッドのオーバーライド、およびすべてのクラスがObject のサブクラスであること(継承の設計と実装は試験範囲外)。
  • 4

    Data Collections · ⁨データコレクション⁩

    Watch lesson · ⁨レッスンを視聴⁩
    4.1

    The Ethics of Collecting Data

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.

    Learning Objective 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.

    Learning Objective 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.
    日本語

    学習目標 4.1.A: コンピュータシステム上で個人データを収集・保存することによるプライバシーへのリスクを説明する。

    • 4.1.A.1 コンピュータを使用する際、個人のプライバシーは危険にさらされます。新しいプログラムを開発する際、プログラマは利用者の個人のプライバシーを守ろうとする努力をするべきです。

    学習目標 4.1.B: データセットを使用する際のデータ品質の認識と潜在的な問題の重要性を説明する。

    • 4.1.B.1 アルゴリズムバイアス とは、特定のユーザーグループに対して不公正な結果を生み出す、プログラム内の体系的かつ反復的なエラーを指します。
    • 4.1.B.2 プログラマは、データセットの収集方法およびこの方法を用いて新たな情報を推論したり結論を導いたりする際に生じる可能性のあるバイアスについて、使用前に理解しておくべきです。
    • 4.1.B.3 一部のデータセットは不完全であるか、不正確なデータを含んでいます。そのようなデータを使用してプログラムを開発または使用すると、プログラムが正しく動作しない、あるいは非効率になることがあります。

    学習目標 4.1.C: 問題を解決したり特定の質問に答えたりするために適切なデータセットを特定する。

    • 4.1.C.1 データセットの内容は特定の質問やトピックに関連している場合がありますが、異なる質問やトピックに対して正しい回答を提供したり情報を推論したりするには適切ではない可能性があります。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語
    Server racks in a data centre — large collections of data raise ethical questions about collection and use
    Server racks in a data centre — large collections of data raise ethical questions about collection and use

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    privacy/ˈprɪvəsi/ プライバシー
    consent/kənˈsent/ 同意
    bias/ˈbaɪəs/ バイアス
    4.2

    Why We Need Data Structures

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 4.2.A: 日常生活で見られるデータセットに関連するパターンやアルゴリズムを、文章や図を用いて表現する。

    • 4.2.A.1 データセットとは、特定の情報の断片やデータの集合体である。
    • 4.2.A.2 データセットは操作・分析することで問題を解決したり質問に回答したりできる。データセットを分析する際は、セット内の値を1つずつアクセス・利用し、その後、所望の結果に応じて処理を行う。
    • 4.2.A.3 データはチャートや表を使用して図で表現できる。この視覚化は、データを操作するために用いるアルゴリズムの計画に使用できる。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    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.

    日本語
    A filing cabinet: collections store many values under one name so algorithms can process them
    A filing cabinet: collections store many values under one name so algorithms can process them

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    data structure/ˈdeɪtə ˈstrʌktʃə/ データ構造
    4.3

    Making and Reading an Array

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 length attribute.
    • 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 for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
    • 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 0 through one less than the length of the array, inclusive. Using an index value outside of this range will result in an ArrayIndexOutOfBoundsException.
    日本語

    学習目標 4.3.A: 関連するデータの集合体を表現するために用いられる、1次元(1D)配列オブジェクトに関するコードを作成する。

    • 4.3.A.1 配列は、同じ型の複数の値を格納する。値はプリミティブ値またはオブジェクト参照のいずれかである。
    • 4.3.A.2 配列の長さは作成時に固定され、変更できない。配列の長さはlength属性を通じてアクセスできる。
    • 4.3.A.3 newキーワードを使用して配列を作成する場合、すべての要素は要素データタイプのデフォルト値で初期化される。intのデフォルト値は0、doubleのデフォルト値は0.0、booleanのデフォルト値はfalse、参照タイプのデフォルト値はnullである。
    • 4.3.A.4 イニシャライザリストを使用して配列を作成・初期化できる。
    • 4.3.A.5 1D配列の要素にアクセス・修正するには、インデックスを使用して四角括弧[ ]を使う。
    • 4.3.A.6 配列の有効なインデックス値は、0から配列の長さの1減った値まで(両端を含む)。この範囲外のインデックス値を使用すると、ArrayIndexOutOfBoundsExceptionが発生する。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An array 数组 is a fixed-size, ordered collection of same-type values. Indices run from 0 to length - 1:

    Accessing an index outside 0..length-1 throws an ArrayIndexOutOfBoundsException.

    日本語

    An array 数组 is a fixed-size, ordered collection of same-type values. Indices run from 0 to length - 1:

    A one-dimensional array (a list) with its indices and bounds
    A one-dimensional array (a list) with its indices and bounds
    int[] 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-1 throws an ArrayIndexOutOfBoundsException.

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    array/əˈreɪ/ 配列
    4.4

    Visiting Every Element of an Array

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 for loop or while loop requires elements to be accessed using their indices.
    • 4.4.A.3 An enhanced for loop header includes a variable, referred to as the enhanced for loop variable. For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
    • 4.4.A.4 Assigning a new value to the enhanced for loop 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 for loop variable. This does not change the object references stored in the array.
    • 4.4.A.6 Code written using an enhanced for loop to traverse elements in an array can be rewritten using an indexed for loop or a while loop.
    日本語

    学習目標 4.4.A: 1D配列の要素を走査するために用いられるコードを作成し、これらの走査の結果を決定する。

    • 4.4.A.1 配列の走査とは、反復文を使用して配列のすべての要素または順序付けられた一連の要素にアクセスすることである。
    • 4.4.A.2 インデックス付きforループまたはwhileループで配列を走査するには、インデックスを使用して要素にアクセスする必要がある。
    • 4.4.A.3 拡張forループヘッダーには、拡張forループ変数と呼ばれる変数が含まれる。拡張forループの各反復において、拡張forループ変数は、インデックスを使用せずに要素のコピーに割り当てられる。
    • 4.4.A.4 拡張forループ変数に新しい値を割り当てても、配列に格納されている値は変わらない。
    • 4.4.A.5 配列がオブジェクト参照を格納している場合、拡張forループ変数に対してメソッドを呼び出すことで属性を修改できる。これは、配列に格納されているオブジェクト参照を変化させない。
    • 4.4.A.6 配列の要素を走査するために拡張forループを使用して記述されたコードは、インデックス付きforループまたはwhileループを使用して書き換えることができる。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    Traverse 遍历 an array with a for loop (gives the index) or an enhanced for / for-each loop (gives each value, read-only):

    日本語

    Traverse 遍历 an array with a for loop (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 value
    
    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Traverse/trəˈvɜːs/ 走査
    4.5

    Standard Array Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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
    日本語

    学習目標 4.5.A: 配列を含む特定の文脈や仕様に対する標準的および独自アルゴリズムのコードを作成し、これらのアルゴリズムの結果を決定する。

    • 4.5.A.1 配列の走査を利用する標準的なアルゴリズムには以下がある:
      • 最小値または最大値を決定する
      • 合計や平均を計算する
      • 少なくとも1つの要素が特定の属性を持つかどうかを判定する
      • 全ての要素が特定の属性を持つかどうかを判定する
      • 特定の属性を持つ要素の数を判定する
      • 連続する要素のペアすべてにアクセスする
      • 重複要素の有無を判定する
      • 要素を左または右へシフトまたは回転させる
      • 要素の順序を逆転させる

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    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 ObjectiveEssential 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 File and Scanner classes.
    • 4.6.A.3 A file can be opened by creating a File object, using the name of the file as the argument of the constructor.
      • File(String str) is the File constructor that accepts a String file name to open for reading, where str is the pathname for the file.
    • 4.6.A.4 When using the File class, 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 add throws IOException to the header of the method that uses the file. If the file name is invalid, the program will terminate.
    • 4.6.A.5 The File and IOException classes are part of the java.io package. An import statement must be used to make these classes available for use in the program.
    • 4.6.A.6 The following Scanner methods and constructor—including what they do and when they are used—are part of the Java Quick Reference:
      • Scanner(File f) is the Scanner constructor that accepts a File for reading.
      • int nextInt() returns the next int read from the file or input source if available. If the next int does not exist or is out of range, it will result in an InputMismatchException.
      • double nextDouble() returns the next double read from the file or input source. If the next double does not exist, it will result in an InputMismatchException.
      • boolean nextBoolean() returns the next boolean read from the file or input source. If the next boolean does not exist, it will result in an InputMismatchException.
      • String nextLine() returns the next line of text as a String read from the file or input source; can return the empty string if called immediately after another Scanner method that is reading from the file or input source.
      • String next() returns the next String read from the file or input source.
      • boolean hasNext() returns true if there is a next item to read in the file or input source; returns false otherwise.
      • 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 nextLine and the other Scanner methods 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 nextLine and other Scanner methods on the same input source is outside the scope of the AP Computer Science A course and exam.
    • 4.6.A.8 The following additional String method—including what it does and when it is used—is part of the Java Quick Reference:
      • String[] split(String del) returns a String array where each element is a substring of this String, which has been split around matches of the given expression del.
      • Exclusion statement: The parameter del uses 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 while loop can be used to detect if the file still contains elements to read by using the hasNext method as the condition of the loop.
    • 4.6.A.10 A file should be closed when the program is finished using it. The close method from Scanner is called to close the file.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    File and IOException live in java.io, so a program that reads a file needs import java.io.*;. Opening a file can fail (it might not exist), and Java forces you to handle that – the simplest way is to add throws IOException to the method header. A Scanner then reads the file line by line, using hasNext... to test before reading:

    import java.io.*;
    ...
    public static void readFile() throws IOException {
        Scanner f = new Scanner(new File("data.txt"));
        while (f.hasNextLine()) {
            String line = f.nextLine();
        }
    }
    

    Reading typed tokens with nextInt(), nextDouble(), or nextBoolean() throws an InputMismatchException if the next token is the wrong type – for example calling nextInt() when the next thing in the file is the word cat.

    4.7

    Wrapping a Number in an Object

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 4.7.A: Develop code to use Integer and Double objects from their primitive counterparts and determine the result of using these objects.

    • 4.7.A.1 The Integer class and Double class are part of the java.lang package. An Integer object is immutable, meaning once an Integer object is created, its attributes cannot be changed. A Double object is immutable, meaning once a Double object 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 int to an Integer and a double to a Double. 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 Integer to an int and a Double to a double. 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 Integer method—including what it does and when it is used—is part of the Java Quick Reference:
      • static int parseInt(String s) returns the String argument as an int.
    • 4.7.A.5 The following class Double method—including what it does and when it is used—is part of the Java Quick Reference:
      • static double parseDouble(String s) returns the String argument as a double.
    日本語

    学習目標 4.7.A: 基本型から Integer および Double オブジェクトを作成し、これらのオブジェクトを使用した場合の結果を決定するコードを作成する。

    • 4.7.A.1 Integer クラスと Double クラスは java.lang パッケージの一部である。Integer オブジェクトは不変であり、一度 Integer オブジェクトが作成されると、その属性を変更することはできない。Double オブジェクトも同様に不変であり、一度 Double オブジェクトが作成されると、その属性を変更することはできない。
    • 4.7.A.2 オートボックス化とは、Javaコンパイラが基本型と対応するオブジェクトラッパークラスの間に自動的に行う変換である。これには、int を Integer に変換することや、double を Double に変換することが含まれる。Javaコンパイラは、基本値が以下の場合にオートボックス化を適用する:
      • 対応するラッパークラスのオブジェクトを期待するメソッドのパラメータとして渡される場合
      • 対応するラッパークラスの変数に割り当てられる場合
    • 4.7.A.3 アンボックス化とは、Javaコンパイラがラッパークラスから基本型へ自動的に行う変換である。これには、Integer を int に変換することや、Double を double に変換することが含まれる。Javaコンパイラは、ラッパークラスのオブジェクトが以下の場合にアンボックス化を適用する:
      • 対応する基本型の値を期待するメソッドのパラメータとして渡される場合
      • 対応する基本型の変数に割り当てられる場合
    • 4.7.A.4 以下のクラス Integer メソッド(その機能と使用時)はJavaクイックリファレンスに含まれる:
      • static int parseInt(String s) は ⟨String⟩ 引数を ⟨int⟩ として返す。
    • 4.7.A.5 以下のクラス Double メソッド(その機能と使用時)はJavaクイックリファレンスに含まれる:
      • static double parseDouble(String s) は ⟨String⟩ 引数を ⟨double⟩ として返す。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    An ArrayList stores objects, not primitives, so a primitive is wrapped in an object: Integer wraps int, Double wraps double. Java does this with autoboxing 自动装箱 (int to Integer) and unboxing (back again) automatically, so you can write list.add(5) and int x = list.get(0).

    日本語

    An ArrayList stores objects, not primitives, so a primitive is wrapped in an object: Integer wraps int, Double wraps double. Java does this with autoboxing 自动装箱 (int to Integer) and unboxing (back again) automatically, so you can write list.add(5) and int x = list.get(0).

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    autoboxing/ˌɔːtəʊˈbɒksɪŋ/ オートボックス化
    4.8

    The ArrayList Toolbox

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential Knowledge

    4.8.A
    Develop code for collections of related objects using ArrayList objects and determine the result of calling methods on these objects.

    • 4.8.A.1 An ArrayList object is mutable in size and contains object references.
    • 4.8.A.2 The ArrayList constructor ArrayList() constructs an empty list.
    • 4.8.A.3 Java allows the generic type ArrayList<E>, where the type parameter E specifies the type of the elements. When ArrayList<E> is specified, the types of the reference parameters and return type when using the ArrayList methods are type E. ArrayList<E> is preferred over ArrayList. 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 ArrayList class is part of the java.util package. An import statement must be used to make this class available for use in the program.
    • 4.8.A.5 The following ArrayList methods—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) appends obj to end of list; returns true.
      • void add(int index, E obj) inserts obj at position index (0 <= index <= size), moving elements at position index and higher to the right (adds 1 to their indices) and adds 1 to size.
      • E get(int index) returns the element at position index in the list.
      • E set(int index, E obj) replaces the element at position index with obj; returns the element formerly at position index.
      • E remove(int index) removes element from position index, moving elements at position index + 1 and higher to the left (subtracts 1 from their indices) and subtracts 1 from size; returns the element formerly at position index.
    • 4.8.A.6 The indices for an ArrayList start at 0 and end at the number of elements - 1.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    What an ArrayList really is

    An ArrayList 动态数组 grows and shrinks as you add or remove items. Declare it with the element type in <>:

    日本語
    What an ArrayList really is

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    ArrayList/əˈreɪ lɪst/ ArrayList
    4.9

    Visiting Every Element of an ArrayList

    Syllabus · ⁨シラバス⁩
    Learning ObjectiveEssential Knowledge

    4.9.A
    Develop code used to traverse the elements of an ArrayList and determine the results of these traversals.

    • 4.9.A.1 Traversing an ArrayList is when iteration or recursive statements are used to access all or an ordered sequence of the elements in an ArrayList.
    • 4.9.A.2 Deleting elements during a traversal of an ArrayList requires 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 ArrayList while traversing it using an enhanced for loop can result in a ConcurrentModificationException. Therefore, when using an enhanced for loop to traverse an ArrayList, you should not add or remove elements.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    Traverse with an index loop or a for-each loop, just like arrays (use size() and get(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 i after a removal – otherwise removing shifts elements left and you skip one. And never add or remove elements while traversing an ArrayList with a for-each loop: changing its size mid-loop throws a ConcurrentModificationException, so use an index loop (backwards, as above) whenever you must remove.

    4.10

    Standard ArrayList Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 4.10.A: Develop code for standard and original algorithms for a particular context or specification that involve ArrayList objects and determine the result of these algorithms.

    • 4.10.A.1 There are standard ArrayList algorithms 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, or ArrayList objects to be traversed simultaneously.
    日本語

    学習目標 4.10.A: ArrayList オブジェクトを含む特定の文脈や仕様のための標準的および独自アルゴリズムのためのコードを作成し、これらのアルゴリズムの結果を決定する。

    • 4.10.A.1 以下のような traversal を利用する標準的な ArrayList アルゴリズムがあります:
      • 最小値または最大値を決定する
      • 合計や平均を計算する
      • 少なくとも1つの要素が特定の属性を持つかどうかを判定する
      • 全ての要素が特定の属性を持つかどうかを判定する
      • 特定の属性を持つ要素の数を判定する
      • 連続する要素のペアすべてにアクセスする
      • 重複要素の有無を判定する
      • 要素を左または右へシフトまたは回転させる
      • 要素の順序を逆転させる
      • 要素を挿入する
      • 要素を削除する
    • 4.10.A.2 いくつかのアルゴリズムでは、複数の String、配列、または ArrayList オブジェクトを同時にtraversalする必要があります。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    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 ObjectiveEssential 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 for int is 0, for double is 0.0, for boolean is false, and for a reference type is null.
    • 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 at arr[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 length attribute. The valid row index values for a 2D array are 0 through 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 the length attribute of one of the rows. The valid column index values for a 2D array are 0 through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array named values, the number of rows is values.length and the number of columns is values[0].length. Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException.

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English

    A 2D array 二维数组 is a grid (rows and columns) – an array of arrays:

    日本語

    A 2D array 二维数组 is a grid (rows and columns) – an array of arrays:

    A two-dimensional array (a table) with row and column indices
    A two-dimensional array (a table) with row and column indices
    int[][] 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;      // 4
    
    Explore · ⁨探索⁩

    Index a 2D array by row and column · ⁨2次元配列を行と列でインデックスする⁩

    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. · ⁨2D配列は[row][col]によって参照されるグリッドです。インデックスを変化させて、どのセルが選択されるか観察してください。行が先、次に列で、どちらも0からカウントされます。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    2D array/ˌtuː ˈdiː əˈreɪ/ 2次元配列
    4.12

    Walking Through a Grid

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 for loops and enhanced for loops 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 for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array. The inner loop traverses a single row. Therefore, the inner enhanced for loop variable must be the same type as the elements stored in the 1D array. Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
    日本語

    学習目標 4.12.A: 2次元配列の要素を走査するコードを開発し、これらの走査の結果を特定する。

    • 4.12.A.1 2次元配列の全要素または順序付けられた一連の要素を走査・アクセスするには、ネストされた反復文を使用する。2次元配列は配列の配列として格納されているため、for ループや改善されたfor ループを用いて2次元配列を走査する方法は、1次元配列オブジェクトと同様である。ネストされた反復文は、2次元配列を行主順、列主順、あるいは一意に定義された順序で走査するように記述できる。行主順とは、各行に沿って走査が行われる2次元配列要素の順序而言い、列主順とは、各列に沿って走査が行われることを指す。
    • 4.12.A.2 2D 配列を遍历 (traverse) するために使用される階層化された增强 for ループの外側ループは行を遍历 する。したがって、增强 for ループ変数は各行の型でなければならず、それは 1D 配列である。内側ループは単一の行を遍历 する。したがって、内側の增强 for ループ変数は、1D 配列に格納されている要素と同じ型でなければならない。增强 for ループ変数に新しい値を割り当てても、配列に格納されている値は変わらない。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Traversing a 2-D array

    Visit every cell with nested loops – the outer over rows, the inner over columns (row-major order 行主序):

    日本語
    Traversing a 2-D array

    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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    row-major order/rəʊ ˈmeɪdʒə ˈɔːdə/ 行主順
    4.13

    Standard 2D Array Algorithms

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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
    日本語

    学習目標 4.13.A: 2次元配列を含む特定のコンテキストまたは仕様に対する標準的かつ独自アルゴリズムのコードを開発し、これらのアルゴリズムの結果を特定する。

    • 4.13.A.1 2次元配列の走査を利用する標準的なアルゴリズムには、以下のものがある:
      • 全要素、または指定された行、列、その他の部分の最小値または最大値を特定する
      • 全要素、または指定された行、列、その他の部分の総和または平均を計算する
      • 2次元配列全体、または指定された行、列、その他の部分に、少なくとも1つの要素が特定の性質を持っているかどうかを特定する
      • 2次元配列全体、または指定された行、列、その他の部分の全要素が特定の性質を持っているかどうかを特定する
      • 2次元配列、または指定された行、列、その他の部分において、特定の性質を持つ要素の個数を特定する
      • 連続する要素のペアすべてにアクセスする
      • 2次元配列、または指定された行、列、その他の部分に重複要素が存在するか否かを特定する
      • 行内の要素を左または右にシフト・回転させる、または列内の要素を上または下にシフト・回転させる
      • 行または列の要素の順序を逆転させる

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    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 · ⁨シラバス⁩
    English

    Learning Objective 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 ArrayList have been checked. Linear search algorithms can begin the search process from either end of the array or ArrayList.
    • 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.
    日本語

    学習目標 4.14.A: コレクション内で特定の情報を検索するために使用される線形探索アルゴリズムのコードを開発し、検索を実行した結果を特定する。

    • 4.14.A.1 線形探索アルゴリズムは、標準的なアルゴリズムであり、希望する値が見つかるか、配列やArrayList の全要素が確認されるまで、順序通り各要素を確認する。線形探索アルゴリズムは、配列やArrayList のどちらの端からでも検索を開始できる。
    • 4.14.A.2 線形探索アルゴリズムを2次元配列に適用する場合、各行にアクセスした後、2次元配列の各行に対して線形探索を適用する必要がある。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Binary search: halve and conquer
    • 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.

    Exam skill: binary search requires sorted data; know how many comparisons it makes and how lo, hi, mid update.

    Worked example. Search for target = 40 in the sorted array {3, 9, 14, 23, 31, 42, 55} (indices 0–6). Start lo=0, hi=6:

    • mid = (0+6)/2 = 3, a[3]=23 < 40, so lo = 4;
    • mid = (4+6)/2 = 5, a[5]=42 > 40, so hi = 4;
    • mid = (4+4)/2 = 4, a[4]=31 < 40, so lo = 5;
    • now lo (5) > hi (4), so the loop ends – 40 is not present.

    Each step halved the range, so even this miss took only three comparisons.

    日本語
    Binary search: halve and conquer
    • 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
    Binary search halves the range at each step
    Linear search checks every element in turn until the target is found
    Linear search checks every element in turn until the target is found
    int 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, mid update.

    Worked example. Search for target = 40 in the sorted array {3, 9, 14, 23, 31, 42, 55} (indices 0–6). Start lo=0, hi=6:

    • mid = (0+6)/2 = 3, a[3]=23 < 40, so lo = 4;
    • mid = (4+6)/2 = 5, a[5]=42 > 40, so hi = 4;
    • mid = (4+4)/2 = 4, a[4]=31 < 40, so lo = 5;
    • now lo (5) > hi (4), so the loop ends – 40 is not present.

    Each step halved the range, so even this miss took only three comparisons.

    Explore · ⁨探索⁩

    Compare 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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Linear search/ˈlɪnɪə sɜːtʃ/ 線形探索
    Binary search/ˈbaɪnəri sɜːtʃ/ 二項探索
    4.15

    Putting Data in Order: Selection and Insertion Sort

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 4.15.A: ソートアルゴリズムの各ステップを実行してコレクションの要素をソートし、その結果を特定する。

    • 4.15.A.1 セレクトソートとインサートソートは、配列やArrayList の要素をソートするために使用できる反復ソートアルゴリズムである。
    • 4.15.A.2 セレクトソートでは、未ソート部分のリストから最も小さい(または最大の)要素を繰り返し選択し、それをソート部分のリストにおける正しい(最終的な)位置に交換する。
    • 4.15.A.3 挿入ソートは、未整列部分のリストから要素を取り出し、整列部分の正しい位置(必ずしも最終的な位置ではない)に移動させる。この際、新しい要素のためのスペースを確保するため、整列部分の要素をシフトする。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Insertion sort
    Bubble sort, pass by pass
    • 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.

    Both are simple and take about $n^2$ steps on average – fine for small arrays. Be able to trace the array after each pass.

    日本語
    Insertion sort
    Bubble sort, pass by pass
    • 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 pass
    An insertion sort, shifting each key into place pass by pass

    Both are simple and take about $n^2$ steps on average – fine for small arrays. Be able to trace the array after each pass.

    Explore · ⁨探索⁩

    Watch 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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Selection sort/sɪˈlekʃn sɔːt/ 選択ソート
    Insertion sort/ɪnˈsɜːʃn sɔːt/ 挿入ソート
    4.16

    Methods That Call Themselves: Recursion

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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.
    日本語

    学習目標 4.16.A: 再帰メソッドの呼び出しによる結果を決定する。

    • 4.16.A.1 再帰メソッドとは、自身を呼び出すメソッドである。再帰メソッドには、少なくとも1つのベースケース(再帰を停止させるもの)と、少なくとも1つの再帰呼び出しが含まれる。再帰は反復の別の形態である。
    • 4.16.A.2 各再帰呼び出しには、パラメータを含む独自のローカル変数のセットがある。パラメータの値は、ループ制御変数の値がループの進行を表すように、再帰プロセスの進行を捉える。
    • 4.16.A.3 いかなる再帰的解法も、反復アプローチの使用によって再現可能であり、逆にその逆も成立する。
      • 対象外: 再帰コードの記述はAPコンピュータサイエンスAのコースおよび試験の対象外である。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Recursion & the call stack

    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:

    Without a reachable base case, recursion never stops (a stack overflow).

    Recursion and iteration are interchangeable. Any recursive solution can be rewritten with a loop (an iterative approach), and any loop can be rewritten with recursion - they solve the same problems. The factorial above is identical in effect to an iterative version:

    So the choice is about clarity, not capability: recursion reads naturally for problems with a self-similar structure (trees, merge sort), while iteration avoids the memory cost of stacking a call frame per step. The exam may ask you to convert one into the other.

    日本語
    Recursion & the call stack

    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).

    Recursion and iteration are interchangeable. Any recursive solution can be rewritten with a loop (an iterative approach), and any loop can be rewritten with recursion - they solve the same problems. The factorial above is identical in effect to an iterative version:

    public static int factorial(int n) {
        int result = 1;
        for (int i = 2; i <= n; i++) result *= i;   // same answer, no self-call
        return result;
    }
    

    So the choice is about clarity, not capability: recursion reads naturally for problems with a self-similar structure (trees, merge sort), while iteration avoids the memory cost of stacking a call frame per step. The exam may ask you to convert one into the other.

    Explore · ⁨探索⁩

    Unfold 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. · ⁨再帰メソッドは、ベースケースに到達するまでより小さい入力に対して自身を呼び出します。その後、結果が上方へ戻っていきます( fold back up)。ステップバイステップで、呼び出しスタックが積まれて展開されていく様子を見てください。⁩

    Vocabulary · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Recursion/rɪˈkɜːʃn/ 再帰
    base case/beɪs keɪs/ 再帰ケース
    4.17

    Recursive Search and Merge Sort

    Syllabus · ⁨シラバス⁩
    English

    Learning Objective 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 String objects, arrays, and ArrayList objects.

    Learning Objective 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 ArrayList and eliminates half of the array or ArrayList in 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.

    Learning Objective 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.
    日本語

    学習目標 4.17.A: ストリングまたはコレクションを使用する再帰アルゴリズムの実行結果を決定する。

    • 4.17.A.1 再帰は、Stringオブジェクト、配列、およびArrayListオブジェクトの走査に使用できる。

    学習目標 4.17.B: コレクション内で情報を検索するために用いられる二項探索アルゴリズムの各反復の結果を決定する。

    • 4.17.B.1 データは二項探索アルゴリズムを使用するために整列された順序にある必要がある。二項探索は、整列された配列やArrayListの中央から始まり、各再帰呼び出しで配列やArrayListの半分を除外し、目的の値が見つかるか、すべての要素が除外されるまで続ける。
    • 4.17.B.2 二項探索は通常、線形探索よりも効率的である。
      • 対象外: 線形探索および二項探索以外の検索アルゴリズムは、APコンピュータサイエンスAのコースおよび試験の対象外である。
    • 4.17.B.3 二項探索アルゴリズムは、反復的に記述することも、再帰的に記述することもできる。

    学習目標 4.17.C: コレクションをソートするために使用されるマージソートアルゴリズムの各反復の結果を決定する。

    • 4.17.C.1 マージソートは、配列やArrayListの要素をソートするために使用できる再帰ソートアルゴリズムである。
      • 対象外: 選択ソート、挿入ソート、およびマージソート以外のソートアルゴリズムは、APコンピュータサイエンスAのコースおよび試験の対象外である。
    • 4.17.C.2 マージソートは、各サブ配列が1つの要素になるまで配列を繰り返し小規模なサブ配列に分割し、その後、整列されたサブ配列を再帰的に統合して、整列された最終的な配列を形成する。

    Source: College Board AP Course and Exam Description · ⁨出典: College Board AP コースおよび試験説明書⁩

    English
    Merge sort: split, then merge

    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.

    Worked 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 returns 1, so the calls unwind inward: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 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.

    日本語
    Merge sort: split, then merge

    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 up
    Merge sort splits the array to single elements, then merges sorted halves back up

    Worked 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 returns 1, so the calls unwind inward: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 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 · ⁨語彙⁩ Train · ⁨練習する⁩
    English 日本語
    Merge sort/mɜːdʒ sɔːt/ マージソート
    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.

Log in or create account · ⁨ログインまたはアカウント作成⁩

IGCSE, A-Level & AP