본문 바로가기
과목

AP 컴퓨터 과학 A

팁

AP 컴퓨터 과학 A는 Java 과정입니다: 객체와 클래스, 기본 데이터 타입과 제어 흐름, 클래스 작성, 배열과 ArrayList, 2D 배열, 상속과 다态성, 그리고 재귀. 이는 가짜 코드가 아닌 실제 객체 지향 코드로 가르치는 첫 번째 프로그래밍 과정입니다.

서술형 문제 4개 모두 손으로 쓴 Java 코드입니다. 컴파일러가 세미콜론 누락이나 잘못된 반환 타입을 잡아주지 않으므로, 복습 중에는 종이에 코드를 쓰십시오. 타이핑하는 것과 다른 기술입니다.

배열과 ArrayList가 가장 많이 출제되는 주제입니다. Traverse, 삽입 및 제거에 유창하고, 요소를 제거할 때 어떤 인덱스가 이동하는지 아는 것이 다른 어떤 연습 시간보다 더 큰 보상을 줍니다.

노트에는 Java로 된 CED 단원이 포함되어 있으며, 브라우저에서 편집할 수 있는 실행 가능한 예제가 있습니다. 과거 FRQ와 점수 기준은 라이브러리에 있으며, 모두 코드 작성이 필요한 문제이므로 풀이 예시는 완전한 메소드 형태입니다.

  • 1

    物体与方法的运用

    수업 보기
    1.1

    알고리즘, 프로그래밍, 컴파일러 introduction

    Syllabus

    학습 목표 1.1.A: 일상생활에서 발견되는 패턴과 알고리즘을 글이나 도표를 사용하여 표현하시오.

    • 1.1.A.1 알고리즘은 과제를 완료하거나 문제를 해결할 때 따르는 단계별 절차를 정의합니다. 이러한 알고리즘은 글이나 도표를 사용하여 표현될 수 있습니다.
    • 1.1.A.2 *순서(Sequencing)*는 과정의 단계들이 수행되는 순서를 정의합니다. 과정의 단계들은 한 번에 하나씩 수행됩니다.

    학습 목표 1.1.B: 코드 컴파일 및 실행 과정을 설명하시오.

    • 1.1.B.1 코드는 어떤 텍스트 에디터에서도 작성할 수 있으나, 프로그래머가 코드를 작성, 컴파일 및 실행할 수 있는 도구를 제공하므로 보통 통합 개발 환경(IDE) 을 사용하여 프로그램을 작성합니다.
    • 1.1.B.2 컴파일러는 코드에 대해 일부 오류를 점검합니다. 컴파일러가 감지할 수 있는 오류는 프로그램 실행 전에 수정되어야 합니다.

    학습 목표 1.1.C: 프로그래밍 오류의 유형을 식별하시오.

    • 1.1.C.1 *구문 오류(Syntax error)*는 프로그래밍 언어의 규칙을 따르지 않는 프로그램 내 실수입니다. 이러한 오류는 컴파일러에 의해 감지됩니다.
    • 1.1.C.2 *논리 오류(Logic error)*는 알고리즘이나 프로그램에서 예상치 못하거나 잘못된 동작을 유발하는 실수입니다. 이러한 오류는 프로그램에 특정 데이터를 입력하여 예상되는 결과가产出되는지 확인함으로써 테스트를 통해 감지됩니다.
    • 1.1.C.3 *실행 중 오류(Run-time error)*는 프로그램 실행 중 발생하는 프로그램 내 실수입니다. 실행 중 오류는 일반적으로 프로그램이 비정상적으로 종료되게 합니다.
    • 1.1.C.4 *예외(Exception)*은 컴파일러에 의해 감지되지 않은 예상치 못한 오류로 인해 발생하는 실행 중 오류의 일종이며, 프로그램 실행의 정상적인 흐름을 중단시킵니다.

    출처: College Board AP Course and Exam Description

    워크스테이션의 소스 코드 – 프로그램은 정확한 지령으로 작성, 컴파일 및 행됩니다
    워크스테이션의 소스 코드 – 프로그램은 정확한 지령으로 작성, 컴파일 및 실행됩니다

    **알고리즘(algorithm)**은 문제를 해결하는 유한하고 단계별 절차입니다. **프로그램(program)**은 컴퓨터가 실행할 수 있는 언어로 알고리즘을 표현한 것입니다. 자바(Java)는 컴파일 compiling됩니다: 컴파일러/compiler가 소스 코드를 **바이트코드(bytecode)**로 변환하고, 이를 **자바 가상 머신(Java Virtual Machine, JVM)**이 실행합니다. 구문 오류(syntax error)(문법 위반)는 컴파일러가 잡지만, 논리 오류(logic error)(잘못된 결과)는 잡지 않습니다 – 프로그램은 실행되지만 예상치 못한 동작을 보입니다.

    컴파일러는 전체 프로그램을 한 번에 번역합니다; 인터프리터interpreter는 줄별로 실행합니다
    컴파일러는 전체 프로그램을 한 번에 번역합니다; 인터프리터interpreter는 줄별로 실행합니다
    아래에서 본 여러 컴퓨터 프로세서 칩
    당신의 자바 프로그램은 이러한 프로세서 중 하나가 실제로 실행하는 지령으로 컴파일됩니다
    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ə/ 문법 오류(syntax error)
    logic error/ˈlɒdʒɪk ˈerə/ 논리 오류(logic error)
    1.2

    변수와 데이터 타입

    Syllabus

    학습 목표 1.2.A: 특정 규격에 가장 적절한 데이터 타입 범주를 식별합니다.

    • 1.2.A.1 데이터 타입은 값의 집합과 해당 값들에 대한 연산들의 집합입니다. 데이터 타입은 기본(primitive) 또는 참조(reference)로 분류할 수 있습니다.
    • 1.2.A.2 이 과정에 사용되는 기본 데이터 타입은 숫자 및布尔 값에 대한 값의 집합과 그에 대응하는 연산들을 정의합니다.
    • 1.2.A.3 참조 유형은 기본 타입이 아닌 객자를 정의하는 데 사용됩니다.

    학습 목표 1.2.B: 숫자 및布尔 값을 저장하기 위해 변수를 선언하는 코드를 작성합니다.

    • 1.2.B.1 본 과정에서 사용하는 세 가지 기본 데이터 타입은 int, double, 그리고 boolean이다. int 값은 정수(int)이다. double 값은 실수(real number)이다. boolean 값은either true 또는 false이다.
      • 제외 사항: 다른 다섯 가지 기본 데이터 타입(long, short, byte, float, 그리고 char)은 AP Computer Science A 과정 및 시험의 범위를 벗어납니다.
    • 1.2.B.2 변수는 프로그램 실행 중값이 변경될 수 있는 저장 위치입니다. 모든 변수에는 이름과 associate된 데이터 타입이 있습니다. 기본 타입의 변수는 해당 타입의 기본 값을 저장합니다.

    출처: College Board AP Course and Exam Description

    **변수(variable)**는 고정된 **타입(type)**의 값을 저장하는 이름이 붙은 상자입니다. 자바의 주요 기본(primitive) 타입은 int(정수), double(소수점 숫자), 그리고 boolean(true/false)입니다. 먼저 타입을 지정하여 선언합니다:

    자바의 기본 데이터 타입, 각기 다른 종류의 값을 저장
    자바의 기본 데이터 타입, 각기 다른 종류의 값을 저장
    int score = 90;
    double price = 4.99;
    boolean passed = true;
    
    탐색하기

    변수가 한 번에 하나의 값을 어떻게 저장하는지 탐색해 보십시오

    변수는 고정된 타입의 단일 값을 저장하는 이름이 붙은 상자로 정의됩니다. 줄을 따라 진행하면 각 상자가 값을 받는 것을 볼 수 있습니다. score를 재할당하면 새로운 상자가 생성되는 것이 아니라 기존 숫자를 위쪽하여 덮어쓴다는 점에 주의하십시오.

    English 한국어
    variable/ˈveərɪəbl/ 变量
    type/taɪp/ 글자
    1.3

    식과 출력

    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.

    출처: College Board AP Course and Exam Description

    **식(expression)**은 값과 **연산자(operator)**를 조합하여 결과를 계산합니다: + - * / 및 % (나머지 연산,余数). 정수 나눈 정수는 절단(truncate)됩니다: 7 / 2는 3이고, 7 % 2는 1입니다. 연산자 우선순위는 수학 규칙(*,/,%이 +,-보다 앞서림)을 따릅니다. 출력하는 방법은 다음과 같습니다:

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

    정수를 정수 0로 나누는 것(7 / 0과 같음)은 허용되지 않으며 실행 시점에 ArithmeticException 오류를 발생시킨다. 문자열 내부에서 백슬래시는 에스케이프 시퀀스를 표시한다: \"은 이중 인용부호를 출력하고, \\은 단일 백슬래시를 출력하며, \n는 새 줄을 시작하므로, System.out.println("She said \"hi\"");는 She said "hi"를 출력한다.

    탐색하기

    연산 순서를 단계별로 탐색해 보십시오

    Java는 *, /, %를 +과 -보다 먼저 적용하며 왼쪽에서 오른쪽으로 계산합니다. 각 단계를 관찰하면 왜 2 + 3 * 4가 $14$이 아니라 $20$인지 이해할 수 있습니다 — 곱하기 연산이 먼저 이루어지기 때문입니다.

    English 한국어
    expression/ekˈspreʃn/ 표현식
    modulus/ˈmɒdjʊləs/ 절댓값(모듈러스)
    escape sequence/eˈskeɪp ˈsiːkwəns/ 회피 시퀀스
    assignment/əˈsaɪnmənt/ 과제 배정
    Casting/ˈkæstɪŋ/ 캐스팅
    library/ˈlaɪbrəri/ 라이브러리(library)
    1.4

    할당 문장과 입력

    Syllabus

    학습 목표 1.4.A: 식이 포함된 할당 문장에 대한 코드를 작성하고, 해당 문장으로 인해 변수에 저장되는 값을 결정합니다.

    • 1.4.A.1 변수는 식 내에서 사용하기 전에 반드시 값을 할당받아야 합니다. 그 값은 호환 가능한 데이터 타입이어야 합니다. 변수는 처음 값을 할당받을 때 초기화됩니다. 참조 유형(new object)이나 객체가 없는 경우 null을 할당할 수 있습니다. 리터럴 null은 참조가 어떤 객체와도 연결되지 않음을 나타내는 데 사용되는 특수한 값입니다.
    • 1.4.A.2 할당 연산자 =을 사용하면 프로그램에서 변수에 저장된 값을 초기화하거나 변경할 수 있습니다. 오른쪽의 식 값이 왼쪽의 변수에 저장됩니다.
      • 제외 사항: 식 내부에서 할당 연산자를 사용하는 것(예: a = b = 4; 또는 a[i += 5])은 AP Computer Science A 과정 및 시험 범위를 벗어납니다.
    • 1.4.A.3 실행 중에는 식이 평가되어 단일 값을 생성합니다. 식의 값은 식 평가 결과에 따라 타입이 결정됩니다.

    학습 목표 1.4.B: 입력을 읽는 코드를 작성합니다.

    • 1.4.B.1 입력은 촉각, 오디오, 시각, 텍스트 등 다양한 형태로 올 수 있습니다. Scanner 클래스는 키보드에서 텍스트 입력을 얻는 방법 중 하나입니다.
      • 제외 사항: 사용자에게서 들어오는 특정 형태의 입력은 AP Computer Science A 과정 및 시험 범위를 벗어납니다.

    출처: College Board AP Course and Exam Description

    대입문 x = expr;는 오른쪽 값을 평가하여 왼쪽 변수에 저장한다. 입력을 받을 때는 Scanner를 사용한다:

    Scanner in = new Scanner(System.in);
    int age = in.nextInt();
    String name = in.next();
    
    1.5

    캐스팅과 변수의 범위

    Syllabus

    학습 목표 1.5.A: 산술 식에서 원시 값을 다른 원시 타입으로 캐스팅하는 코드를 작성하고, 결과로 생성되는 값을 결정합니다.

    • 1.5.A.1 캐스팅 연산자 (int)과 (double)을 사용하여 double 값에서 int 값으로(또는 그 반대로) 변환할 수 있습니다.
    • 1.5.A.2 double 값을 int 값으로 캐스팅하면 소수점右边的 digits가 잘려 버립니다.
    • 1.5.A.3 일부 코드는 int 값이 자동으로 double 값으로 확장(cast widening)되게 합니다.
    • 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의 정수 값은 메모리에서 유한한 양(4바이트)으로 저장되는 타입 int의 값으로 표현됩니다. 따라서 int 값은 Integer.MIN_VALUE부터 Integer.MAX_VALUE까지의 범위 내에 있어야 합니다(경계 포함).
    • 1.5.B.3 식이 허용된 범위 밖의 int 값으로 평가되면 정수 오버플로우가 발생합니다. 결과는 허용된 범위 내의 int 값이지만, 반드시 예상한 값은 아닙니다.

    학습 목표 1.5.C: 식의 정확도를 제한하는 조건을 설명합니다.

    • 1.5.C.1 컴퓨터는 데이터 타입에 따라 데이터를 저장하기 위해 지정된 양의 메모리를 할당합니다. 식이 할당된 메모리 양에 저장될 수 있는 것보다 더 정밀한 double으로 평가되면 반올림 오차가 발생합니다. 결과는 표현 가능한 값으로 반올림됩니다. 자연스럽게 발생하는 반올림 오차를 피하려면 int 값을 사용하십시오.
      • 제외 사항: 반올림 오차를 피하는 데 사용할 수 있는 다른 특수 소수 타입은 AP Computer Science A 과정 및 시험 범위를 벗어납니다.

    출처: College Board AP Course and Exam Description

    int 범위, 오버플로우 및 절사

    각 타입은 고정된 범위를 가지며, int는 약 2.1억을 넘어오면 오버플로우합니다. 캐스팅은 타입 간 변환입니다. 확장(int에서 double으로)은 자동이며, 축소에는 명시적인 캐스팅이 필요하며 이는 절단(반올림하지 않음)합니다:

    double avg = (double) total / count;   // force real division
    int whole = (int) 3.9;                 // 3, truncated
    

    exam skill: 소수점이 예상되었을 때 정수 나누기로 인해 절사된 결과가 나오는 것을 주의하십시오 – 한 항을 먼저 double로 캐스팅하십시오.

    Worked example. 각 식을 추적(trace)하십시오:

    • 7 / 2 → 3 (모두 int이므로 나누기는 버림);
    • 7.0 / 2 → 3.5 (하나의 double이 실수 나누기를 강제합니다);
    • 7 % 2 → 1 (나머지);
    • (double) 7 / 2 → 3.5 (타입 변환이 /보다 우선순위가 높으므로, 이 연산은 7.0 / 2);
    • (double) (7 / 2) → 3.0 (괄호는 먼저 7 / 2 = 3를 계산한 후, int first에서 확장합니다).

    마지막 두 가지가 비슷해 보이지만 다릅니다. 타입 변환의 위치가 truncate(절단)가 일어나는지 여부를 결정합니다.

    탐색하기

    int와 double이 숫자를 다르게 저장하는 이유

    int는 고정된 범위 내의 정수만 저장합니다. 반대로 double는 mantissa(유효숫자)와 exponent(지수)를 저장하여 정확성은 포기하고 대신 매우 넓은 범위를 확보합니다. double를 int로 형 변환하면 소수점이 버려지며, 값이 int의 범위를 넘으면 오버플로우가 발생합니다.

    1.6

    복합 대입 연산자

    Syllabus

    학습 목표 1.6.A: 복합 할당 연산자가 포함된 할당 문장에 대한 코드를 작성하고, 해당 문장으로 인해 변수에 저장되는 값을 결정합니다.

    • 1.6.A.1 복합 할당 연산자 +=, -=, *=, /=, %=는 수치 식에서 할당 연산자의 대용으로 사용할 수 있습니다. 복합 할당 연산자는 왼쪽 값과 오른쪽 값 사이에서 지시된 산술 연산을 수행한 후 결과를 왼쪽 변수에 할당합니다.
    • 1.6.A.2 포스트 증감 연산자 ++과 포스트 감감 연산자 --은 수치 변수에 저장된 값에 1을 더하거나 1을 뺍니다. 새로운 값이 변수에 할당됩니다.
      • 제외 사항: AP Computer Science A 과정 및 시험 범위에는 전위(prefix) 형식(예: ++x)으로 사용되는 증감 연산자(increment and decrement operators)와 다른 식 내부(예: arr[x++])에서 사용되는 증감 연산자의 사용이 포함되지 않는다.

    출처: College Board AP Course and Exam Description

    축약형은 연산과 대입을 결합합니다: x += 5은 x = x + 5을 의미합니다. similarly -=, *=, /=, %=도同理입니다. 증가(increment) 및 감소(decrement) 연산자 x++와 x--는 값에 1을 더하거나 뺍니다.

    1.7

    애플리케이션 프로그래밍 인터페이스(API) 및 라이브러리

    Syllabus

    학습 목표 1.7.A: API에 포함된 라이브러리에 있는 클래스의 속성과 동작을 식별합니다.

    • 1.7.A.1 라이브러리는 클래스들의 모음입니다. 응용 프로그램 인터페이스(API) 규격은 프로그래머에게 해당 클래스들을如何使用하는지 안내합니다. API 규격과 라이브러리에 있는 문서화 내용은 API로 정의된 클래스의 속성과 동작을 이해하는 데 필수적입니다. 클래스는 특정 참조 유형을 정의합니다. API 및 라이브리의 클래스들은 패키지为单位 grouping됩니다. 기존 클래스와 클래스 라이브리를 활용하여 객체를 생성할 수 있습니다.
    • 1.7.A.2 속성은 클래스와 관련된 데이터를 의미하며 변수에 저장됩니다. 동작은 클래스의 인스턴스가 할 수 있는 일(또는 그 인스턴스에 대해 할 수 있는 일)을 의미하며 메서드에 의해 정의됩니다.

    출처: College Board AP Course and Exam Description

    API(Application Programming Interface)는 사용자가 사용할 수 있는 클래스와 메서드의 공개된 목록입니다. 라이브러리는 미리 만든 클래스들의 모음(예: Math, String, Scanner)입니다. API 문서를 읽으면 메서드가需要什么参数(parameters)를 필요로 하는지, 무엇을 반환하는지 알 수 있으며 내부 코드는 볼 수 없습니다. 이는 추상화(abstraction) 의 예시입니다.

    English 한국어
    abstraction/əbˈstrækʃn/ 추상화
    Comments/ˈkɒments/ 주석
    Interface/ˈɪntəfeɪs/ 인터페이스
    1.8

    주석으로 작성된 문서

    Syllabus

    학습 목표 1.8.A: 주석을 통해 코드의 기능과 사용법을 설명합니다.

    • 1.8.A.1 주석은 원본 프로그래머와 다른 프로그래머가 코드와 그 기능을 이해하도록 작성되지만, 컴파일러에서는 무시되며 프로그램 실행 시에도 실행되지 않습니다. Java의 세 가지 유형의 주석에는 /* */이 있으며, 이는 주석 블록을 생성합니다; //이 있으며, 이는 한 줄에 대한 주석을 생성합니다; 그리고 /** */인 Javadoc 주석은 API 문서화를 생성하는 데 사용됩니다.
    • 1.8.A.2 전제 조건은 메서드가 예상대로 작동하기 위해 메서드 실행 직전에 참이어야 하는 조건입니다. 전제 조건이 충족되었는지 확인하기 위해 메서드가 체크할 것이라는 기대는 없습니다.
    • 1.8.A.3 후건 조건은 메서드 실행 후 항상 참이어야 하는 조건입니다. 후건 조건은 반환되는 값이나 객체의 속성의 현재 값을 통해 실행 결과를 묘사합니다.

    출처: College Board AP Course and Exam Description

    주석(comment) 은 컴파일러에 의해 무시되지만 IEnumerable에게 코드를 설명합니다: single line에는 //, block에는 /* ... */, 그리고 메서드의 목적, 매개변수, 반환 값을 문서화하는 Javadoc comment에는 /** ... */를 사용합니다. 정확한 전제 조건(preconditions) 과 사후 조건(postconditions) 을 여기에 기록합니다.

    1.9

    메서드 서명

    Syllabus

    학습 목표 1.9.A: 문서화와 메서드 서명을 바탕으로 올바른 메서드를 식별합니다.

    • 1.9.A.1 메서드는 호출될 때만 실행되는 이름이 붙은 코드 블록입니다. 코드 블록은 braces(중괄호)로 둘러싸인 코드의 어떤 부분입니다. 절차 추상화는 메서드가 어떻게 작성되었는지 알지 못하더라도 메서드가 무엇을 하는지 알면 프로그래머가 메서드를 사용할 수 있게 해줍니다.
    • 1.9.A.2 파라미터는 메서드 또는 컨스트럭터 헤더에 선언된 변수이며 메서드 본체 내부에서 사용할 수 있습니다. 이를 통해 값이나 인자가 메서드나 컨스트럭터에 전달되어 사용될 수 있습니다. 파라미터가 있는 메서드의 메서드 서명은 메서드명과 파라미터 타입의 순서 목록으로 구성됩니다. 파라미터가 없는 메서드의 메서드 서명은 메서드명과 빈 파라미터 목록으로 구성됩니다.

    학습 목표 1.9.B: 메서드를 호출하는 방법을 설명합니다.

    • 1.9.B.1 void 메서드는 반환값이 없으므로 따라서 식의 일부로 호출되지 않습니다.
    • 1.9.B.2 비-void 메서드는 헤더의 반환 타입과 동일한类型的返回值를 반환합니다. 비-void 메서드를 호출할 때 반환값을 사용하려면, 이를 변수에 저장하거나 식의 일부로 사용해야 합니다.
    • 1.9.B.3 인자는 메서드가 호출될 때 메서드로 전달되는 값입니다. 메서드에 전달되는 인자는 메서드 서명의 파라미터 목록에 명시된 타입과 숫자 및 순서에 호환되어야 합니다. 메서드를 호출할 때 인자는 pass by value 방식을 사용하여 전달됩니다. Pass by value는 인자의 복사본으로 파라미터를 초기화합니다.
    • 1.9.B.4 여러 개의 메서드가 같은 이름을 가지고 있지만 서로 다른 서명을 가질 때, 이러한 메서드들은 오버로딩되었다고 말합니다.
    • 1.9.B.5 메서드 호출은 문장의 순차적 실행을 중단시켜, 먼저 메서드 내의 문장을 실행한 후 계속 진행하게 만듭니다. 메서드의 마지막 문장이 실행되거나 return文이 실행되면, 제어 흐름은 메서드가 호출된 지점 바로 다음으로 돌아갑니다.

    출처: College Board AP Course and Exam Description

    메서드 서명(method signature) 은 메서드의 이름과 매개변수 타입을 뜻하며, 예: nextInt() 또는 substring(int, int). 메서드를 호출하려면 number, type, order가 매개변수와 일치하는 인자(arguments) 를 제공해야 합니다. 메서드 헤더(전체 선언문) 또한 반환 유형(return type) 을 명시합니다—메서드가 돌려주는 값의 타입(없으면 void)—하지만 반환 유형은 서명에 포함되지 않으므로 두 메서드가 반환 유형만으로 구분될 수 없습니다.

    English 한국어
    method signature/ˈmeθəd ˈsɪɡnɪtʃə/ 메서드 서명
    arguments/ˈɑːɡjuːmənts/ 인자(arguments)
    class (static) method/klæs ˈmeθəd/ 클래스 (정적) 메서드
    1.10

    클래스 메서드 호출

    Syllabus

    학습 목표 1.10.A: 클래스 메서드를 호출하는 코드를 작성하고 해당 호출의 결과를 판단할 수 있다.

    • 1.10.A.1 클래스 메서드는 클래스 인스턴스가 아닌 클래스 자체에 연결된다. 클래스 메서드에는 메서드 이름 앞의 헤더에 static 키워드가 포함된다.
    • 1.10.A.2 클래스 메서드는 일반적으로 클래스명과 함께 점(.) 연산자를 사용하여 호출한다. 메서드 호출이 정의된 클래스 내에서 이루어지는 경우, 호출 시 클래스명을 사용하는 것은 선택 사항이다.

    출처: College Board AP Course and Exam Description

    클래스(static) 메서드는 클래스 자체에 속하므로, 클래스 이름을 통해 호출합니다: ClassName.method(args). 인스턴스 객체가 필요 없습니다.

    탐색하기

    스택에서 클래스 메소드 호출을 따라가십시오

    Math.max와 같은 클래스 메소드를 호출하면 새로운 프레임이 호출 스택에 적재됩니다; 메소드가 값을 반환하면 해당 프레임이 제거되고 제어가 호출자에게 돌아갑니다. 스택이 커지고 작아지는 과정을 단계별로 관찰하십시오.

    English 한국어
    class/klæs/ 클래스
    1.11

    Math 클래스

    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.

    출처: College Board AP Course and Exam Description

    Math class는 정적(math) 메서드를 제공합니다: Math.abs(x), Math.pow(base, exp), Math.sqrt(x), 그리고 Math.random() (a double in $[0,1)$). 0부터 n-1까지 무작위 정수를 얻으려면: (int)(Math.random() * n)를 사용하십시오.

    1.12

    객체: 클래스의 인스턴스

    Syllabus

    학습 목표 1.12.A: 클래스와 객체 간의 관계를 설명할 수 있다.

    • 1.12.A.1 객체는 정의된 속성을 가진 클래스의 구체적인 인스턴스이다. 클래스는 객체의 속성과 행동에 대한 공식적인 구현 또는 청사진이다.
    • 1.12.A.2 관련 클래스들의 공통 속성과 행동을 하나의 초기(superclass)라 불리는 클래스에 넣음으로써 클래스 계층 구조를 구축할 수 있다. 초기를 확장하는 *하위(subclass)*는 코드 내에서 기존 속성과 행위를 대체하지 않고도 이를 활용할 수 있다. 이는 하위로부터 초기로의 상속 관계를 형성한다.
      • 배제 문구: 상속 관계의 설계 및 구현은 AP Computer Science A 과정 및 시험의 범위를 벗어난다.
    • 1.12.A.3 Java의 모든 클래스는 Object 클래스의 하위 클래스이다.

    학습 목표 1.12.B: 참조 유형을 저장하기 위한 변수를 선언할 수 있는 코드를 작성할 수 있다.

    • 1.12.B.1 참조 유형의 변수는 객체 참조를 보유하며, 이를 해당 객체의 메모리 주소라고 생각할 수 있다.

    출처: College Board AP Course and Exam Description

    =는 객체가 아닌 참조를 복사함

    클래스(class) 는 설계도(blueprint)이고, 객체(object) 는 이를 바탕으로 constructed된 구체적인 인스턴스(instance) 입니다. 클래스는 데이터(fields) 와 동작(methods) 을 묶어놓는데, 이것이 オブジェクト指向プログラミング(object-oriented programming) 의 핵심입니다. String, Scanner, 그리고 ArrayList는 모두 인스턴스를 생성할 수 있는 classes입니다.

    클래스는 계층 구조로 조직될 수 있다. 초기 superclass는 여러 하위 subclass들이 extend它时它 – 继承关系。Java의 모든 클래스는 최종적으로 내장된 Object 클래스의 하위 클래스이므로, 모든 객체는 이미 toString方法来 가집니다; 초기 superclass와 동일한 서명(signature)을 가진 하위 클래스 메소드를 작성하는 것은 **메소드 오버라이딩(method overriding)**입니다. (사용자가 직접 상속 구조를 설계하는 것은 이 과정의 범위를 벗어나지만, 이러한 용어를 식별할 수 있어야 합니다.)

    클래스 도식:-private 속성과 public 메서드
    클래스 도식: -private 속성과 public 메서드
    클래스는 설계도이며, 각 객체는 이를 기반으로 한 하나의 인스턴스입니다
    클래스는 설계도이며, 각 객체는 이를 기반으로 한 하나의 인스턴스입니다
    English 한국어
    object/ˈɒbdʒekt/ 물체 자체
    instance/ˈɪnstəns/ 인스턴스
    object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ 객체 지향 프로그래밍(object-oriented programming)
    superclass/ˈsuːpəklæs/ 초기 superclass
    subclasses/ˈsʌbklæsɪz/ 하위 클래스
    inheritance relationship/ɪnˈherɪtəns rɪˈleɪʃənʃɪp/ 상속 관계
    method overriding/ˈmeθəd ˌəʊvəˈraɪdɪŋ/ 메서드 오라이딩
    reference/ˈrefrəns/ 기준계
    1.13

    객체 생성 및 저장(인스턴시네이션)

    Syllabus

    학습 목표 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 생성자 인자는 생성자가 호출될 때 생성자에 전달되는 값이다. 생성자에 전달되는 인자는 생성자 서명의 매개변수 목록에 명시된 유형과 순서 및 개수가 호환되어야 한다. 생성자를 호출할 때는値传递(calling by value) 방식으로 인자를 전달한다. 値传递은 인자의 복사본으로 매개변수를 초기화한다.
    • 1.13.C.4 생성자 호출은 명령어들의 순차적 실행을中断打断使程序首先执行生成器中的语句然后再继续。生成器中的最后一个语句执行后,控制权返回到生成器调用点之后的位置。

    출처: College Board AP Course and Exam Description

    인스턴시네이션(instantiation) 은 new 키워드를 사용하여 객체를 생성하고 콘스트럭터(constructor) 를 호출합니다:

    Scanner in = new Scanner(System.in);
    String s = new String("hi");   // or just "hi"
    

    변수는 객체 그 자체가 아니라 참조(reference) (对象的地址)를 저장합니다. 두 개의 참조가 같은 객체를 가리킬 수 있습니다; ==으로 비교하면 내용而非地址을 비교하는 것이 아니라 주소를 비교합니다.

    참조가 아무것도 가리키지 않을 수도 있습니다: 특수 값 null은 "어떤 객체에도 연결되어 있지 않음"을 의미합니다. null 참조에 메서드를 호출하면 run time에 NullPointerException이 발생합니다. 이를 방지하기 위해 ==/!=로 테스트하고 null을 먼저 확인하여, 메서드가 실행되기 전에 &&이 short-circuit되도록 하십시오: if (s != null && s.length() > 0).

    원시(primitive) 변수는 값을 직접持有, 참조는 객체를 향하는 화살표를 가짐
    원시 변수는 값을 직접持有, 참조는 객체를 향하는 화살표를 가짐
    English 한국어
    Instantiation/ˌɪnstænʃɪˈeɪʃn/ 인스턴스화
    constructor/kənˈstrʌktə/ 생성자
    null/nʌl/ null
    instance method/ˈɪnstəns ˈmeθəd/ 인스턴스 메소드(instance method)
    1.14

    인스턴스 메서드 호출

    Syllabus

    학습 목표 1.14.A: 인스턴스 메서드를 호출하는 코드를 작성하고 이러한 호출의 결과를 판단할 수 있다.

    • 1.14.A.1 인스턴스 메서드는 해당 클래스의 객체에서 호출된다. 인스턴스 메서드를 호출할 때 점(.) 연산자와 함께 객체명을 사용한다.
    • 1.14.A.2 null 참조에 대한 메서드 호출은 NullPointerException을 초래한다.

    출처: College Board AP Course and Exam Description

    인스턴스 메서드는 특정 객체에 대해 작동하므로, 객체 참조를 통해 호출합니다: object.method(args). 예: in.nextInt(), word.length().

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

    출처: College Board AP Course and Exam Description

    문자열은 불변(immutable)

    String 객체는 불변(immutable) — 메서드는 원본을 변경하지 않고 새로운(new) 문자열을 반환합니다. 주요 메서드(모든 인덱스는 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
    

    시험 기술: substring(a, b)는 인덱스 a을 포함하지만 포함하지 않습니다(excludes) b, 그리고 String 비교에는 .equals을 use해야 하며, ==을 use해서는 안 됩니다—가장 많이 출제되는 두 가지 String 함정입니다.

    해설 예시. String s = "COMPUTER";라고 합시다 (인덱스 0–7). 그러면 s.length()은 8이고; s.substring(0, 4)은 "COMP"입니다 (인덱스 0,1,2,3 – 인덱스 4 제외); s.substring(4)은 "UTER"입니다 (인덱스 4부터 끝까지); s.indexOf("PU")은 3이며; s.indexOf("X")은 -1입니다 (발견되지 않음). substring의 제외된 종점을 세는 것이 가장 흔한 실수입니다.

    0에서 length()-1 사이의 인덱스를 요청하면(bad substring or charAt arguments, e.g. here s.substring(0, 20)), StringIndexOutOfBoundsException이 발생하며 crash합니다—이것은 배열 인덱스 오류의 String cousin입니다.

    String 인덱스는 0에서 시작합니다
    String 인덱스는 0에서 시작합니다
    탐색하기

    문자열 인덱스와 슬라이싱을 탐색해 보십시오

    모든 문자에는 인덱스가 있으며, 번호는 0부터 시작합니다. 시작점과 끝점을 드래그하여 substring(from, to)가 from부터 시작하여 — 하지만 포함하지 않고 — to까지의 문자들을 가져오는 방식을 확인하십시오.

    English 한국어
    immutable/ɪˈmjuːtəbl/ 불변(immutable)
    1.15

    시험 팁

    • 줄마다 수동으로 코드를 trace하고 각 변수의 값을 표에 기록하십시오—시험에서는 추측보다 careful tracing이 점수를 받습니다.
    • Java의 primitive types를 알고, 정수除法가 truncation됨을 알 것 ($7/2$ gives $3$); 실제除法를 위해 cast나 double을 사용하십시오.
    • 컴파일 타임 오류(문법, 타입)와 런타임 오류를 구분한다. 명명된 오류를 기억해야 한다: ArithmeticException (int ÷ 0), NullPointerException (null 참조에 대한 메서드 호출), StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException – 그리고 로직 오류(잘못된 출력).
    • 연산자 우선순위를 따르고, 변수를 사용할 전에 반드시 초기화한다.
    • 자유 서술형 문제에서는 완전하고 컴파일 가능한 Java 코드를 작성하라. 올바른 반환 타입을 사용하고 메서드 헤더와 정확히 일치시켜라.
    English 한국어
    primitive types/ˈprɪmɪtɪv taɪps/ 원시 유형(primitive types)
  • 2

    선택 및 반복

    수업 보기
    2.1

    Selection and Repetition in Algorithms

    Syllabus

    학습 목표 2.1.A: 일상생활에서 발견되는 선택과 반복이 포함된 패턴과 알고리즘을 문자나 도표를 사용하여 표현합니다.

    • 2.1.A.1 알고리즘의 기본 요소로는 순서, 선택, 반복이 포함됩니다.
    • 2.1.A.2 알고리즘은 의사결정을 통한 선택과 루프를 통한 반복을 포함할 수 있습니다.
    • 2.1.A.3 선택은 알고리즘의 실행 경로에 대한 선택이 참 또는 거짓의 의사결정에 기반할 때 발생합니다.
    • 2.1.A.4 반복은 원하는 결과가 달성될 때까지 프로세스가 반복되는 것입니다.
    • 2.1.A.5 순서, 선택, 반복이 사용되는 순서는 알고리즘의 결과에 기여합니다.

    출처: College Board AP Course and Exam Description

    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
    English 한국어
    control structures/kənˈtrəʊl ˈstrʌktʃəz/ 제어 구조
    selection/sɪˈlekʃn/ 선택
    iteration/ˌɪtəˈreɪʃn/ 반복(iteration)
    2.2

    Boolean Expressions

    Syllabus

    학습 목표 2.2.A: 관계 연산자를 사용하여 부등식을 생성하는 코드를 작성하고 이 부등식의 결과를 결정한다.

    • 2.2.A.1 값은 같은지 여부를 확인하기 위해 관계 연산자 == 및 !=을 사용하여 비교할 수 있다. 원시 타입인 경우 실제 원시 값을 비교하며, 참조 타입인 경우 객체 참조를 비교한다.
    • 2.2.A.2 숫자 값은 값 간의 관계를 확인하기 위해 관계 연산자 <, >, <=, 그리고 >=을 사용할 수 있다.
    • 2.2.A.3 관계 연산자가 포함된 식은 부등식 값을 산출한다.

    출처: College Board AP Course and Exam Description

    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
    탐색하기

    AND 진리표를 탐색해 보십시오

    부울表达式의 결과는 true 또는 false입니다. AND는 두 피연산자가 모두 참일 때만 참입니다. 입력을 전환하여 네 가지 경우 모두를 확인하십시오.

    English 한국어
    boolean expression/ˈbuːlɪən ekˈspreʃn/ 부울리안 표현식
    relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/ 관계 연산자(relational operators)
    2.3

    The if Statement

    Syllabus
    Learning ObjectiveEssential Knowledge

    2.3.A
    Develop code to represent branching logical processes by using selection statements and determine the result of these processes.

    • 2.3.A.1 Selection statements change the sequential execution of statements.
    • 2.3.A.2 An 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.

    출처: College Board AP Course and Exam Description

    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
    탐색하기

    if 문장이 어떤 분기 path를 선택하는지 확인해 보십시오

    if 문장은 조건이 참일 때만 본문을 실행하며, 그렇지 않으면 else로 건너뜁니다. 점수를 경계선 사이에서滑动하여 등급이 어떻게 변하는지 관찰하십시오.

    English 한국어
    if statement/ɪf ˈsteɪtmənt/ if 문장(if statement)
    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.

    출처: College Board AP Course and Exam Description

    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.

    출처: College Board AP Course and Exam Description

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

    English 한국어
    Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/ 논리 연산자
    short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/ 단락 평가(short-circuit evaluation)
    2.6

    Comparing Boolean Expressions

    Syllabus

    학습 목표 2.6.A: 동등한 부등식을 비교한다.

    • 2.6.A.1 모든 경우에서 동일한 값으로 평가될 때 두 부등식은 *동등(equivalent)*하다. 진리표(truth tables)를 사용하여 부등식이 동등함을 증명할 수 있다.
    • 2.6.A.2 *데 모르강의 법칙(De Morgan's law)*을 부등식에 적용하여 동등한 부등식을 만들 수 있다. 데 모르강의 법칙에 따르면 부등식 !(a && b)은 !a || !b과 동등하며, 부등식 !(a || b)은 !a && !b과 동등하다.

    학습 목표 2.6.B: 부등식을 사용하여 객체 참조를 비교하는 코드를 작성하고 이 부등식의 결과를 결정한다.

    • 2.6.B.1 서로 다른 변수가 동일한 객체에 대한 참조를 가질 수 있다. 객체 참조는 == 및 !=을 사용하여 비교할 수 있다.
    • 2.6.B.2 객체 참조는 실제로 객체를 참조하는지 확인하기 위해 null, == 또는 !=과 함께 비교할 수 있다.
    • 2.6.B.3 클래스는 클래스의 두 객체 간 동등성에 대한 기준을 지정하는 데 사용할 수 있는 자체 equals 메서드를 정의하는 경우가 많다. 두 객체의 동등성은 대개 두 객체의 속성을 사용하여 결정된다.
      • 배제 문장: equals 메서드를 오버라이딩하는 것은 AP Computer Science A 과정 및 시험의 범위를 벗어납니다.

    출처: College Board AP Course and Exam Description

    De Morgan's laws 德摩根定律 rewrite negations: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Two boolean expressions are equivalent if they give the same result for every input – a truth table proves it. Simplifying conditions this way is a common exam task.

    English 한국어
    De Morgan's laws/də ˈmɔːɡənz lɔːz/ 데摩根의 법칙들
    2.7

    while Loops

    Syllabus

    학습 목표 2.7.A: 원하는 결과를 얻기 위해 반복 프로세스가 필요한 시점을 식별합니다.

    • 2.7.A.1 *반복(Iteration)*은 일종의 재현입니다. 반복 문장은 루프를 제어하는 부등식이 true인 동안 코드 세그먼트를 0회 이상 반복하여 제어 흐름을 변경합니다.
    • 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로 평가될 때까지 계속되며, 이때 반복이 종료됩니다.

    출처: College Board AP Course and Exam Description

    A while loop 循环 repeats while its condition stays true, testing before each pass. You must change something inside so the loop eventually stops, or it becomes an infinite loop 无限循环:

    The three loop types differ in where the condition is tested
    The three loop types differ in where the condition is tested
    int i = 0;
    while (i < 5) {
        System.out.println(i);
        i++;
    }
    
    탐색하기

    while 루프를 추적해 보십시오

    while 루프는 조건이 참인 동안 반복되며, 매 회차마다 변수를 업데이트합니다. 제곱합이 쌓이는 과정을 단계별로 확인하십시오.

    English 한국어
    while loop/waɪl luːp/ while 루프(while loop)
    infinite loop/ˈɪnfɪnət luːp/ 무한 루프(infinite loop)
    2.8

    for Loops

    Syllabus

    학습 목표 2.8.A: for 루프를 사용하여 반복 프로세스를 표현하는 코드를 작성하고 이 프로세스의 결과를 결정합니다.

    • 2.8.A.1 for 루프는 반복 문장의 일종입니다. for 루프 헤더에는 세 가지 부분이 있습니다: 초기화, 부등식, 업데이트.
    • 2.8.A.2 for 루프에서 초기화 문장은 첫 번째 부등식 평가 전에 단 한 번만 실행됩니다. 초기화되는 변수를 루프 제어 변수라고 합니다. 부등식은 루프 제어 변수가 초기화된 직후 즉시 평가되고, 이후 증분 문장이 실행될 때마다 평가되어 false가 됩니다. 각 반복에서 업데이트는 전체 루프 본체가 실행된 후, 부등식이 다시 평가되기 전에 실행됩니다.
    • 2.8.A.3 for 루프는 등가한 while 루프로(또는 그 반대로) 변환할 수 있습니다.

    출처: College Board AP Course and Exam Description

    A for loop packs initialization, condition, and update into one line – best when you know the count:

    for (int i = 0; i < n; i++) {
        // runs n times, i = 0..n-1
    }
    

    A 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
    탐색하기

    for 루프를 추적해 보십시오

    for 루프는 고정된 횟수만큼 실행되며, 카운터가 범위를 따라 이동합니다. 카운터와 누적 합계가 한 회차씩 증가하는 것을 관찰하십시오.

    2.9

    Building Complete Selection and Iteration Algorithms

    Syllabus

    학습 목표 2.9.A: 표준 및 독창적인 알고리즘(데이터 구조 제외)을 위한 코드를 작성하고 이 알고리즘의 결과를 결정합니다.

    • 2.9.A.1 표준 알고리즘은 다음을 수행할 수 있습니다:
      • 정수가 다른 정수에 의해 나뉘는지 또는 나뉘지 않는지를 식별
      • 정수 내 개별 숫자를 식별
      • 특정 기준이 충족되는 빈도를 결정
      • 최소값 또는 최대값을 결정
      • 합계 또는 평균을 계산

    출처: College Board AP Course and Exam Description

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

    int max = arr[0];
    for (int k = 1; k < arr.length; k++) {
        if (arr[k] > max) max = arr[k];
    }
    

    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.

    English 한국어
    flag/flæɡ/ 플래그
    2.10

    String Algorithms

    Syllabus

    학습 목표 2.10.A: 문자열이 포함된 표준 및原创 알고리즘을 위한 코드를 개발하고 이 알고리즘의 결과를 결정합니다.

    • 2.10.A.1 표준 문자열 알고리즘에는 다음을 위한 것이 있습니다:
      • 하나 이상의 하위 문자열이 특정 성질을 가지는지 찾기
      • 특정 기준에 부합하는 하위 문자열의 개수 결정
      • 문자를 반전하여 새로운 문자열 만들기

    출처: College Board AP Course and Exam Description

    Loop through a string by index to process each character:

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        // count vowels, reverse, check for a substring, ...
    }
    

    Typical tasks: count occurrences, build a reversed or filtered copy, or test whether one string contains another.

    2.11

    Nested Iteration

    Syllabus

    학습 목표 2.11.A: 중첩된 반복 프로세스를 표현하는 코드를 작성하고 이 프로세스의 결과를 결정한다.

    • 2.11.A.1 중첩 반복문은 다른 반복문의 본문에 있는 반복문이다. 루프가 다른 루프 안에 중첩될 때, 안쪽 루프는 바깥쪽 루프가 다음 반복으로 진행하기 전에 모든 반복을 완료해야 한다.

    출처: College Board AP Course and Exam Description

    A nested loop 嵌套循环 puts one loop inside another; the inner loop completes fully for each pass of the outer. If the outer runs $n$ times and the inner $m$ times, the body runs $n\times m$ times – the basis for processing grids and comparing all pairs.

    English 한국어
    nested loop/ˈnestɪd luːp/ 중첩 루프
    2.12

    Informal Run-Time Analysis

    Syllabus

    학습 목표 2.12.A: 문장 실행 횟수를 계산하고 반복문에 대한 비형식적 실행 시간을 비교한다.

    • 2.12.A.1 문장 실행 횟수는 프로그램이 문장을 실행하는 횟수를 나타낸다. 문장 실행 횟수는 주로 반복문의 추적을 통해 비형식적으로 계산된다.

    출처: College Board AP Course and Exam Description

    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.

    탐색하기

    알고리즘의 확장성을 비교해 보십시오

    실행 시간은 입력 크기 $n$에 따라 단계 수가 어떻게 증가하는지를 설명합니다. $n$을 증가시키면 선형 $O(n)$가 이차 $O(n^2)$보다 훨씬 빠르게 앞서는 것을 볼 수 있습니다.

    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

    클래스 생성

    수업 보기
    3.1

    Abstraction and Program Design

    Syllabus

    학습 목표 3.1.A: 자연어 사용 또는 도표 작성을 통해 프로그램의 설계를 표현하며, 모든 속성과 거동을 포함하여 각 클래스에서 발견되는 데이터 및 절차적 추상화를 나타냅니다.

    • 3.1.A.1 추상화는 핵심 개념에 집중함으로써 복잡성을 줄이는 과정입니다. 현재 질문에 관련 없는 세부 사항을 숨기고 관련有用的인 세부 사항들을 통합함으로써 추상화는 복잡성을 줄이고 아이디어에 집중할 수 있게 합니다.
    • 3.1.A.2 데이터 추상화는 데이터 유형의 추상적 속성과 그 표현의 구체적 세부 사항 사이의 분리를 제공합니다. 데이터 추상화는 표현의 구체적인 세부 사항을 참조하지 않고 데이터를 이름만 부여하여 복잡성을 관리합니다. 데이터는 단일 변수 또는 클래스나 데이터 집합과 같은 데이터 모음의 형태로 존재할 수 있습니다.
    • 3.1.A.3 속성은 메서드나 컨스트럭터 외부의 클래스 내에서 정의되는 데이터 추상화의 일종입니다. 인스턴스 변수는 클래스의 각 인스턴스에 대해 고유한 값을 가지는 속성입니다. 클래스 변수는 클래스의 모든 인스턴스가 공유하는 속성입니다.
    • 3.1.A.4 절차적 추상화는 프로세스에 이름을 부여하여该方法을 사용하는 데 있어 그것이 어떻게 이루어지는지가 아닌 무엇이 이루어지는지만 알 수 있게 합니다. 메서드 분해를 통해 프로그래머는 더 큰 클래스 거동을 작은 거동으로 분리하여 각 개별 작은 거동을 표현하는 메서드를 생성합니다. 절차적 추상화는 코드를 복제하는 대신 공통적인 기능을 추출하여 기능을 일반화할 수 있습니다. 이는 코드 재사용을 가능하게 하여 복잡성 관리를 돕습니다.
    • 3.1.A.5 매개변수를 사용하면 절차를 일반화할 수 있으며, 이를 통해 procedures를 다양한 입력 값이나 인자 với 함께 재사용할 수 있습니다.
    • 3.1.A.6程序中 procedural abstraction을 사용하면 메서드 서명과该方法이 수행하는 내용이 유지되는 한该方法 사용자에게 변경 사항을 통보할 필요 없이该方法 내부 구조를 변경(속도 향상, 효율성 증가, 저장 공간 감소 등)할 수 있습니다.
    • 3.1.A.7 클래스를 구현하기 전에 속성과 거동을 포함하여 각 클래스의 설계를 세우는 것이 유용합니다. 이 설계는 자연어 또는 도표를 사용하여 표현할 수 있습니다.

    출처: College Board AP Course and Exam Description

    A jigsaw in progress: classes and methods are modular pieces of a larger program design
    A jigsaw in progress: classes and methods are modular pieces of a larger program design

    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.

    Decomposing a program into modules and sub-modules
    Decomposing a program into modules and sub-modules
    English 한국어
    Abstraction/əbˈstrækʃn/ 추상화(Abstraction)
    3.2

    The Impact of Program Design

    Syllabus

    학습 목표 3.2.A: 컴퓨팅 시스템의 사회적 및 윤리적 함의를 설명합니다.

    • 3.2.A.1 시스템 신뢰성은 명시된 조건 하에서 프로그램이 예상대로 작업을 수행하며 고장 없이 작동하는 능력을 의미합니다. 프로그래머는 다양한 조건으로 프로그램을 테스트하여 시스템 신뢰성을 극대화하려는 노력을 기울여야 합니다.
    • 3.2.A.2 프로그램의 개발은 사회, 경제, 문화에 영향을 미칩니다. 이러한 영향은 긍정적일 수도 있고 부정적일 수도 있습니다. 특정 필요를 충족시키거나 문제를 해결하기 위해 설계된 프로그램은 의도한 용도를 넘어 예상치 못한 부정적 효과를 낳을 수 있습니다.
    • 3.2.A.3 프로그램을 개발할 때 법적 문제와 지적 재산권 관련 이슈가 발생합니다. 프로그래머는 종종 다른 사람이 작성하고 오픈 소스로 공개하여 무료로 사용할 수 있는 코드를 재사용합니다. 오픈 소스로 공개되지 않은 코드를 포함할 경우 프로그래머는 해당 코드의 사용 허가를 얻어야 하며, 일반적으로 통합 전에 코드를 구매해야 합니다.

    출처: College Board AP Course and Exam Description

    Design choices affect whether code is correct, readable, and reusable. Encapsulation 封装 – keeping data private and exposing it only through methods – protects an object's state from misuse and lets you change the inside without breaking users of the class. Thoughtful naming, single-purpose methods, and testing reduce bugs.

    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.

    English 한국어
    Encapsulation/ɪnˌkæpsjʊˈleɪʃn/ encapsulation(캡슐화)
    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/ 오픈소스
    3.3

    The Anatomy of a Class

    Syllabus

    학습 목표 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로 지정된 메서드는 클래스 내부에서만 접근할 수 있습니다.

    출처: College Board AP Course and Exam Description

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

    A class diagram: private attributes and public methods
    A class diagram: private attributes and public methods
    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
    }
    
    A blueprint: a class is a template that defines how objects of that type are built
    A blueprint: a class is a template that defines how objects of that type are built
    탐색하기

    객체의 필드를 상자처럼 보기

    클래스는 관련 데이터(필드)와 메소드를 묶습니다. 각 객체는 자체 필드 상자 세트를 가지며, 하나에 할당하는 것은 그 객체에만 영향을 미칩니다.

    English 한국어
    instance variables/ˈɪnstəns ˈveərɪəblz/ 인스턴스 변수
    3.4

    Constructors

    Syllabus

    학습 목표 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입니다.

    출처: College Board AP Course and Exam Description

    A constructor 构造函数 has the same name as the class and no return type. It runs when you write new, and its job is to initialize the fields. A class can have several constructors with different parameter lists (overloading 重载); a no-argument constructor sets defaults.

    English 한국어
    constructor/kənˈstrʌktə/ 생성자
    overloading/ˌəʊvəˈləʊdɪŋ/ 오버로딩
    3.5

    Methods: How to Write Them

    Syllabus

    학습 목표 3.5.A: 기본数据类型과 객체 참조를 사용하여 클래스 내에 작성된 메서지를 통해 객체의 행동을 정의하고, 해당 메서지를 호출했을 때의 결과를 판별할 수 있는 코드를 작성합니다.

    • 3.5.A.1 void 메서드는 값을 반환하지 않습니다. 헤더에는 메서드 이름 앞에 void 키워드가 포함됩니다.
    • 3.5.A.2 비공백 메서드는 단일 값을 반환합니다. 헤더에는 void 키워드 대신 반환 타입이 포함됩니다.
    • 3.5.A.3 비공백 메서드에서는 반환 타입과 호환되는 반환 식이 평가되어 값이 반환됩니다. 이를 값에 의한 반환이라고 합니다.
    • 3.5.A.4 return 키워드는 제어를 메서드나 컨스트럭터가 호출되었던 지점으로 되돌리는 데 사용됩니다. 리턴 문장 이후에 순차적으로 배치된 코드 절대 실행되지 않습니다. 선택문이나 반복문 내부에서 리턴 문을 실행하면 해당 문장이 중단되고 메서드나 컨스트럭터에서 탈출하게 됩니다.
    • 3.5.A.5 액세서 메서드는 다른 클래스의 객체가 인스턴스 변수 또는 클래스 변수의 값 사본을 얻을 수 있게 해줍니다. 액세서 메서드는 비공백 메서드입니다.
    • 3.5.A.6 뮤테이터(수정자) 메서드는 인스턴스 변수 또는 클래스 변수의 값을 변경하는 메서드입니다. 뮤테이터 메서드는 주로 공백 메서드입니다.
    • 3.5.A.7 매개변수가 있는 메서드는 해당 매개변수를 통해 값을 받아 메서드의 작업을 수행하는 데 사용합니다.
    • 3.5.A.8 인자가 기본数据类型인 경우, 매개변수는 해당 값의 사본으로 초기화됩니다. 매개변수에 대한 변경은 대응하는 인자에 영향을 주지 않습니다.

    출처: College Board AP Course and Exam Description

    A method has a signature, a return type, and a body. An accessor (getter) 访问器 returns information without changing the object; a mutator (setter) 修改器 changes a field. A method returning a value must have a return of the right type on every path; a void method returns nothing.

    public void setScore(int s) { score = s; }   // mutator
    public String toString() { return name + ": " + score; }
    
    탐색하기

    메소드 호출과 반환을 따라가십시오

    메소드를 호출하면 매개변수가 포함된 프레임이 적재됩니다; return에 도달하면 프레임이 제거되고 값이 호출자에게 반환됩니다.

    English 한국어
    accessor (getter)/əkˈsesə/ 액세서(게터)
    mutator (setter)/mjuːˈteɪtə/ 뮤테이터(세터)
    3.6

    Passing and Returning References of an Object

    Syllabus

    학습 목표 3.6.A: 객체 참조를 사용하여 클래스 내에 작성된 메서지를 통해 객체의 행동을 정의하고, 해당 메서드를 호출했을 때의 결과를 판별할 수 있는 코드를 작성합니다.

    • 3.6.A.1 인자가 객체 참조일 경우, 매개변수는 해당 참조의 복사본으로 초기화되며, 객체 자체의 새로운 독립적 복사본을 생성하지는 않습니다. 매개변수가 가변 객체를 참조하는 경우, 메소드 또는 컨스트럭터는 이 참조를 사용하여 객체의 상태를 변경할 수 있습니다. 명세서에 명시된 경우가 아니라면 매개변수로 전달된 가변 객체를 수정하지 않는 것이 좋은 프로그래밍 관례입니다.
    • 3.6.A.2 반환 식이 객체 참조를 평가할 경우, 객체의 새로운 복사본에 대한 참조가 아닌 실제 객체 참조가 반환됩니다.
    • 3.6.A.3 매개변수가 객체에 대한 참조를持有하고 있는 경우, 해당 매개변수가 메소드를 포함하는 클래스와 동일한 타입이 아닌 한, 메소드는 해당 매개변수의私有 데이터 및 메소드에 접근할 수 없습니다.

    출처: College Board AP Course and Exam Description

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

    Java passes by value: the method gets a copy; true pass by reference, which Java lacks, would let it reassign the caller's variable
    Java always passes by value (left): the method gets a copy of the reference. True pass by reference (right) — which Java does not have — would let a method reassign the caller's own variable.

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

    public static void tweak(Student a) {
        a.setScore(100);          // (1) mutates the shared object
        a = new Student("Z", 0);  // (2) repoints the local copy only
        a.setScore(5);            // (3) changes only the new local object
    }
    

    Line (1) changes the object 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.

    3.7

    Class Variables and Class Methods

    Syllabus

    학습 목표 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로 선언하면 그 값을 변경할 수 없습니다.

    출처: College Board AP Course and Exam Description

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

    English 한국어
    static (class) variable/ˈstætɪk ˈveərɪəbl/ 정적 (클래스) 변수
    3.8

    Scope and Access

    Syllabus

    학습 목표 3.8.A: 코드 내에서 변수를 사용할 수 있는 위치를 설명합니다.

    • 3.8.A.1 로컬 변수는 블록(코드 단락)의 헤더나 본体内에 선언된 변수입니다. 로컬 변수는 선언된 블록 내에서만 접근할 수 있습니다. 컨스트럭터와 메소드는 코드 블록이기 때문에, 컨스트럭터 또는 메소드의 매개변수도 로컬 변수로 간주됩니다. 이러한 변수는 컨스트럭터 또는 메소드 내부에서만 사용 가능하며, public 또는 private로 선언될 수 없습니다.
    • 3.8.A.2 로컬 변수 또는 매개변수와 인스턴스 변수의명이 동일한 경우, 컨스트럭터 또는 메소드 본문 내에서는 변수 이름이 인스턴스 변수 대신 로컬 변수를 가리킵니다.

    출처: College Board AP Course and Exam Description

    Scope 作用域 is where a name is visible. A local variable declared in a method exists only inside it; a parameter exists only in its method; an instance variable is visible throughout the object. Access modifiers control visibility across classes: private (this class only) versus public (anywhere). Local variables shadow fields of the same name – a source of bugs.

    A global variable is visible everywhere; a local variable only inside its block
    A global variable is visible everywhere; a local variable only inside its block
    English 한국어
    Scope/skəʊp/ 범위
    3.9

    The this Keyword

    Syllabus

    학습 목표 3.9.A: 자기 참조(self-referencing) 표현에 대한 코드를 작성하고, 이러한 표현의 결과를 결정합니다.

    • 3.9.A.1 인스턴스 메소드 또는 컨스트럭터 내에서 this 키워드는 현재 객체(메소드 또는 컨스트럭터가 호출된 객체)에 대한 참조를持有하는 특수 변수 역할을 합니다.
    • 3.9.A.2 this 키워드를 사용하여 현재 객체를 메소드 호출 시 인자로 전달할 수 있습니다.
    • 3.9.A.3 클래스 메소드는 this 참조를 가지지 않습니다.

    출처: College Board AP Course and Exam Description

    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:

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

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

    3.9

    Exam tips

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

    데이터 컬렉션

    수업 보기
    4.1

    The Ethics of Collecting Data

    Syllabus

    학습 목표 4.1.A: 컴퓨터 시스템에서 개인 데이터를 수집하고 저장하는 것으로부터 발생하는 프라이버시 위험을 설명합니다.

    • 4.1.A.1 컴퓨터를 사용할 때 개인 프라이버시가 위협받을 수 있습니다. 새로운 프로그램을 개발할 때 프로그래머는 사용자의 개인 프라이버시를 보호하기 위해 노력해야 합니다.

    학습 목표 4.1.B: 데이터 세트를 사용할 때 데이터 품질과 잠재적 문제를 인식하는 중요성을 설명합니다.

    • 4.1.B.1 *알고리즘 편향(algorithmic bias)*은 특정 사용자 집단에 대해 불공정한 결과를 초래하는 프로그램 내의 체계적이고 반복적인 오류를 의미합니다.
    • 4.1.B.2 프로그래머는 데이터를 사용하여 새로운 정보를 추론하거나 결론을 도출하기 전에 데이터셋 수집 방법과该方法 사용 시 발생할 수 있는 편향 가능성을 인지해야 합니다.
    • 4.1.B.3 일부 데이터셋은 불완전하거나 부정확한 데이터를 포함할 수 있습니다. 이러한 데이터를 프로그램 개발이나 사용에 적용하면 프로그램이 올바르게 작동하지 않거나 비효율적으로 작동할 수 있습니다.

    학습 목표 4.1.C: 문제를 해결하거나 특정 질문에 답하기 위해 적합한 데이터셋을 식별합니다.

    • 4.1.C.1 데이터셋의 내용은 특정 질문이나 주제와 관련이 있을 수 있으며, 다른 질문이나 주제에 대해 정확한 답변을 제공하거나 정보를 추론하는 데 적합하지 않을 수 있습니다.

    출처: College Board AP Course and Exam Description

    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.

    English 한국어
    privacy/ˈprɪvəsi/ privacy
    consent/kənˈsent/ 동의(consent)
    bias/ˈbaɪəs/ bias
    4.2

    Why We Need Data Structures

    Syllabus

    학습 목표 4.2.A: 일상생활에서 발견되는 데이터셋을 포함하는 패턴 및 알고리즘을 텍스트 또는 도표를 사용하여 표현한다.

    • 4.2.A.1 *데이터셋(data set)*은 특정 정보 조각이나 데이터의 모음집이다.
    • 4.2.A.2 데이터셋은 문제를 해결하거나 질문에 답하기 위해 조작 및 분석할 수 있다. 데이터셋을 분석할 때는 집합 내의 값을 하나씩 액세스하여 사용하며, 이후 원하는 결과에 따라 처리된다.
    • 4.2.A.3 데이터는 차트나 표를 사용하여 도표로 표현할 수 있다. 이 시각 자료는 데이터를 조작할 알고리즘을 계획하는 데 사용될 수 있다.

    출처: College Board AP Course and Exam Description

    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.

    English 한국어
    data structure/ˈdeɪtə ˈstrʌktʃə/ 데이터 구조(data structure)
    4.3

    Making and Reading an Array

    Syllabus

    학습 목표 4.3.A: 관련 데이터의 모음을 1차원(1D) 배열 객체를 사용하여 표현하는 코드를 작성한다.

    • 4.3.A.1 *배열(array)*은 동일한 유형의 여러 값을 저장한다. 값은 기본(primitive) 값일 수도 있고 객체 참조일 수도 있다.
    • 4.3.A.2 배열의 길이는 생성 시에 결정되며 변경할 수 없다. 배열의 길이는 length 속성을 통해 액세스할 수 있다.
    • 4.3.A.3 new 키워드를 사용하여 배열을 생성하면 모든 요소가 해당 요소 데이터 타입의 초기값으로 초기화된다. int의 초기값은 0이며, double의 초기값은 0.0이며, boolean의 초기값은 false이며, 객체 참조 유형(referential type)의 초기값은 null이다.
    • 4.3.A.4 초기화 목록(initializer list)을 사용하여 배열을 생성하고 초기화할 수 있다.
    • 4.3.A.5 대괄호 [ ]은 인덱스를 사용하여 1D 배열의 요소를 액세스하고 수정하는 데 사용된다.
    • 4.3.A.6 数组的有效索引值为从0到数组长度减一之间的整数,包含边界值。使用超出此范围的索引值将导致ArrayIndexOutOfBoundsException错误。

    출처: College Board AP Course and Exam Description

    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.

    English 한국어
    array/əˈreɪ/ 배열 (array)
    4.4

    Visiting Every Element of an Array

    Syllabus

    학습 목표 4.4.A: 1D 배열의 요소를 순회하는 코드를 작성하고 이러한 순회의 결과를 판단한다.

    • 4.4.A.1 *배열 순회(arrays traversing)*는 반복 문장을 사용하여 배열의 모든 요소 또는 순서대로 나열된 일부 요소를 액세스하는 것이다.
    • 4.4.A.2 인덱스 기반 for 루프 또는 while 루프를 사용하여 배열을 순회하려면 요소를 인덱스로 액세스해야 한다.
    • 4.4.A.3 확장(eenhanced) for 루프 헤더에는 확장 for 루프 변수라고 불리는 변수가 포함된다. 확장 for 루프의 각 반복 시, 확장 for 루프 변수는 인덱스를 사용하지 않고 요소의 복사본을 할당받는다.
    • 4.4.A.4 확장 for 루프 변수에 새로운 값을 할당하면 배열에 저장된 값이 변경되지 않는다.
    • 4.4.A.5 배열이 객체 참조를 저장할 때, 확장 for 루프 변수에 대한 메서드 호출을 통해 속성을 수정할 수 있다. 이는 배열에 저장된 객체 참조를 변경하지는 않는다.
    • 4.4.A.6 배열의 요소를 순회하기 위해 확장 for 루프를 사용하여 작성한 코드는 인덱스 기반 for 루프 또는 while 루프를 사용하여 다시 작성할 수 있다.

    출처: College Board AP Course and Exam Description

    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
    
    English 한국어
    Traverse/trəˈvɜːs/ 탐색
    4.5

    Standard Array Algorithms

    Syllabus

    학습 목표 4.5.A: 배열이 포함된 특정 맥락이나 규격에 대한 표준 및 독창적인 알고리즘을 위한 코드를 작성하고, 이러한 알고리즘의 결과를 결정할 수 있다.

    • 4.5.A.1 배열 순환(traversals)을 이용하는 표준 알고리즘에는 다음이 포함된다:
      • 최소값 또는 최대값을 결정
      • 합계 또는 평균을 계산
      • 최소 하나 이상의 요소가 특정 속성을 가는지 확인하기 위해
      • 모든 요소가 특정 속성을 가는지 확인하기 위해
      • 특정 속성을 가진 요소의 개수를 확인하기 위해
      • 모든 연속된 쌍(element pairs)에 접근하기 위해
      • 중복 요소의 존재 여부 여부를 확인하기 위해
      • 요소를 왼쪽 또는 오른쪽으로 이동하거나 회전시키기 위해
      • 요소의 순서를 뒤집기 위해

    출처: College Board AP Course and Exam Description

    Master these patterns: compute a sum or average, find the max/min, count items meeting a condition, check for a duplicate, and reverse or shift elements. Each is a traversal with a running result:

    int sum = 0;
    for (int v : a) sum += v;
    double avg = (double) sum / a.length;
    
    4.6

    Reading Data from a Text File

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

    출처: College Board AP Course and Exam Description

    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

    학습 목표 4.7.A: 기본(type primitive) 대응체로부터 ⟨Integer⟩ 및 ⟨Double⟩ 객체를 사용하여 코드를 작성하고, 이러한 객체를 사용할 때의 결과를 결정할 수 있다。

    • 4.7.A.1 ⟨Integer⟩ 클래스와 ⟨Double⟩ 클래스는 ⟨java.lang⟩ 패키지에 속해 있다。Integer 객체는 불변(immutable)이며, 즉 한 번 ⟨Integer⟩ 객체가 생성되면 그 속성을 변경할 수 없다。Double 객체는 불변이며, 즉 한 번 ⟨Double⟩ 객체가 생성되면 그 속성을 변경할 수 없다。
    • 4.7.A.2 *오토박싱(Autoboxing)*은 Java 컴파일러가 기본 타입과 그에 해당하는 객체 위패러 클래스 사이에서 자동으로 수행하는 변환이다。이것은 ⟨int⟩를 ⟨Integer⟩로 변환하고, ⟨double⟩를 ⟨Double⟩로 변환하는 것을 포함한다。Java 컴파일러는 다음 시에 오토박싱을 적용한다:
      • 매개변수로 전달될 때 해당 위패러 클래스의 객체를 기대하는 메서드에
      • 해당 위패러 클래스의 변수에 할당될 때
    • 4.7.A.3 * 언박싱(Unboxing)*은 Java 컴파일러가 위패러 클래스에서 기본 타입으로 자동으로 수행하는 변환이다。이것은 ⟨Integer⟩를 ⟨int⟩로 변환하고, ⟨Double⟩를 ⟨double⟩로 변환하는 것을 포함한다。Java 컴파일러는 다음 시에 언박싱을 적용한다:
      • 매개변수로 전달될 때 해당 기본 타입의 값을 기대하는 메서드에
      • 해당 기본 타입의 변수에 할당될 때
    • 4.7.A.4 다음クラスInteger메서드(그들이 하는 일과 사용 시점 포함)는 Java Quick Reference에 포함되어 있다:
      • ⟨static int parseInt(String s)⟩는 ⟨String⟩ 인자를 ⟨int⟩로返回。
    • 4.7.A.5 다음クラスDouble메서드(그들이 하는 일과 사용 시점 포함)는 Java Quick Reference에 포함되어 있다:
      • ⟨static double parseDouble(String s)⟩는 ⟨String⟩ 인자를 ⟨double⟩로返回。

    출처: College Board AP Course and Exam Description

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

    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.

    출처: College Board AP Course and Exam Description

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

    출처: College Board AP Course and Exam Description

    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

    학습 목표 4.10.A: ArrayList 객체가 포함된 특정 컨텍스트 또는 명세서를 위한 표준 및原创 알고리즘에 대한 코드를 작성하고, 이러한 알고리즘의 결과를 결정합니다.

    • 4.10.A.1 traversal(회전/탐색)을 사용하는 표준 ArrayList 알고리즘에는 다음이 포함됩니다:
      • 최소값 또는 최대값을 결정
      • 합계 또는 평균을 계산
      • 최소 하나 이상의 요소가 특정 속성을 가는지 확인하기 위해
      • 모든 요소가 특정 속성을 가는지 확인하기 위해
      • 특정 속성을 가진 요소의 개수를 확인하기 위해
      • 모든 연속된 쌍(element pairs)에 접근하기 위해
      • 중복 요소의 존재 여부 여부를 확인하기 위해
      • 요소를 왼쪽 또는 오른쪽으로 이동하거나 회전시키기 위해
      • 요소의 순서를 뒤집기 위해
      • 요소를 삽입하기 위해
      • 요소를 삭제하기 위해
    • 4.10.A.2 일부 알고리즘은 여러 String, 배열, 또는 ArrayList 객체를 동시에 traversal해야 하는 경우가 있습니다.

    출처: College Board AP Course and Exam Description

    The same algorithms as arrays – max/min, count, sum – plus insertion and deletion that arrays cannot do easily. A common task is to remove all elements matching a condition, handling the index-shift carefully.

    4.11

    Grids: Two-Dimensional Arrays

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

    출처: College Board AP Course and Exam Description

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

    A two-dimensional array (a table) with row and column 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
    
    탐색하기

    2D 배열을 행과 열로 인덱싱

    2D 배열은 [row][col]로 주소 지정된 격자입니다. 인덱스를 움직이면的行과 열을 따라 선택되는 셀을 확인하십시오 — 행이 먼저, 그다음 열이며, 둘 다 0부터 세는 점에 유의하십시오.

    English 한국어
    2D array/ˌtuː ˈdiː əˈreɪ/ 2차원 배열
    4.12

    Walking Through a Grid

    Syllabus
    Learning ObjectiveEssential Knowledge

    4.12.A
    Develop code used to traverse the elements in a 2D array and determine the result of these traversals.

    • 4.12.A.1 Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using 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.

    출처: College Board AP Course and Exam Description

    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]);
    
    English 한국어
    row-major order/rəʊ ˈmeɪdʒə ˈɔːdə/ 행 우선 순서(row-major order)
    4.13

    Standard 2D Array Algorithms

    Syllabus

    학습 목표 4.13.A: 2D 배열이 포함된 특정 컨텍스트나 사양에 대한 표준 및 원시 알고리즘을 위한 코드를 작성하고 이 알고리즘의 결과를 예측합니다.

    • 4.13.A.1 2D 배열 순회를 이용하는 표준 알고리즘에는 다음이 포함됩니다:
      • 모든 요소에 대해 또는 지정된 행, 열, 기타 하위 영역에 대해 최소값 또는 최대값을 결정함
      • 모든 요소에 대해 또는 지정된 행, 열, 기타 하위 영역에 대해 합계 또는 평균을 계산함
      • 전체 2D 배열 또는 지정된 행, 열, 기타 하위 영역에서 적어도 하나의 요소가 특정 속성을 가는지 여부 확인
      • 2D 배열 또는 지정된 행, 열, 기타 하위 영역의 모든 요소가 특정 속성을 가는지 여부 확인
      • 2D 배열 또는 지정된 행, 열, 기타 하위 영역에서 특정 속성을 가진 요소의 수를 결정함
      • 모든 연속된 쌍(element pairs)에 접근하기 위해
      • 2D 배열 또는 지정된 행, 열, 기타 하위 영역에 중복 요소가 존재하지 않는지 여부 확인
      • 행의 요소를 좌우로 이동하거나 열의 요소를 상하로 이동
      • 행 또는 열의 요소 순서를 반대로 뒤집기

    출처: College Board AP Course and Exam Description

    Typical grid tasks: sum a row or column, find the max in the grid, count matching cells, or sum a diagonal (where r == c). Each is a nested traversal with a running result.

    4.14

    Finding a Value: Linear and Binary Search

    Syllabus

    학습 목표 4.14.A: 집합 내에서 특정 정보를 검색하기 위한 선형 검색 알고리즘을 위한 코드를 작성하고 검색 실행 결과를 예측합니다.

    • 4.14.A.1 선형 검색 알고리즘은 원하는 값이 발견되거나 배열 또는 ArrayList의 모든 요소가 확인될 때까지 순서대로 각 요소를 확인하는 표준 알고리즘입니다. 선형 검색 알고리즘은 배열 또는 ArrayList의 양 끝 중 어느 쪽에서든 검색을 시작할 수 있습니다.
    • 4.14.A.2 선형 검색 알고리즘을 2D 배열에 적용할 때는 각 행에 접근한 후 2D 배열의 각 행에 대해 선형 검색을 적용해야 합니다.

    출처: College Board AP Course and Exam Description

    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.

    탐색하기

    선형 검색과 이진 검색을 비교해 보십시오

    선형 검색은 요소를 차례로 확인합니다. 반면 이진 검색은每一步로 정렬된 목록을 절반으로 줄입니다. 이진 검색이 목표값에 훨씬 적은 비교로 도달하는 것을 관찰하십시오.

    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

    학습 목표 4.15.A: 집합의 요소를 정렬하기 위한 정렬 알고리즘의 각 단계 실행 결과를 예측합니다.

    • 4.15.A.1 선택 정렬(selection sort)과 삽입 정렬(insertion sort)은 반복적인 정렬 알고리즘으로, 배열 또는 ArrayList의 요소를 정렬하는 데 사용할 수 있습니다.
    • 4.15.A.2 선택 정렬은 미정렬된 부분에서 가장 작은(또는 가장 큰) 요소를 반복적으로 선택하여 정렬된 부분의 올바른(최종) 위치로 스왑합니다.
    • 4.15.A.3 *삽입 정렬(insertion sort)*은 정렬되지 않은 부분의 요소를 정렬된 부분의 올바른(반드시 최종적이지는 않은) 위치로 삽입하기 위해, 새로운 요소를 위한 공간을 만들기 위해 정렬된 부분의 요소들을 이동시킨다.

    출처: College Board AP Course and Exam Description

    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.

    탐색하기

    정렬 알고리즘이 목록을 순서대로 배열하는 과정을 관찰하십시오

    sort는 요소를 순서대로 재배열합니다. 선택/삽입 정렬을 단계별로 따라가면 정렬된 영역이 요소 하나씩 커지는 것을 볼 수 있습니다.

    English 한국어
    Selection sort/sɪˈlekʃn sɔːt/ 선택 정렬
    Insertion sort/ɪnˈsɜːʃn sɔːt/ 삽입 정렬
    4.16

    Methods That Call Themselves: Recursion

    Syllabus

    학습 목표 4.16.A: 재귀 메서드를 호출했을 때의 결과를 판단한다.

    • 4.16.A.1 재귀 메서드는 자신을 호출하는 메서드이다. 재귀 메서드는 최소 하나의 기본 사례(base case)를 포함하며, 이는 재귀를 중단하고, 최소 하나의 재귀 호출을 포함한다. 재귀는 반복의 다른 형태이다.
    • 4.16.A.2 각 재귀 호출은 자체적인 로컬 변수 세트를 가지며, 매개변수도 포함한다. 매개변수 값은 재귀 과정의 진전을 포착하며, 이는 루프 제어 변수 값이 루프의 진전을 포착하는 것과 유사하다.
    • 4.16.A.3 어떤 재귀 해결책도 반복적(iterative) 접근법을 사용하여 복제할 수 있으며, 그 반대도 가능하다.
      • 제외 사항: 재귀 코드를 작성하는 것은 AP 컴퓨터 과학 A 과정 및 시험 범위를 벗어난다.

    출처: College Board AP Course and Exam Description

    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.

    탐색하기

    재귀 호출을 unfolds(펼쳐보기)합니다

    재귀 메소드는 베이스 케이스에 도달할 때까지 더 작은 입력에 대해 자신을 호출한 후 결과를 위로 fold(접어올리기)합니다. 호출이 쌓이고 풀리는 과정을 단계별로 관찰하십시오.

    English 한국어
    Recursion/rɪˈkɜːʃn/ 재귀
    base case/beɪs keɪs/ 베이스 케이스
    4.17

    Recursive Search and Merge Sort

    Syllabus

    학습 목표 4.17.A: 문자열이나 컬렉션을 사용하는 재귀 알고리즘을 실행했을 때의 결과를 판단한다.

    • 4.17.A.1 재귀는 String 객체, 배열 및 ArrayList 객체를 순회(traverse)하는 데 사용할 수 있다.

    학습 목표 4.17.B: 컬렉션에서 정보를 검색하기 위해 사용되는 이진 탐색 알고리즘의 각 반복에 대한 결과를 판단한다.

    • 4.17.B.1 이진 탐색 알고리즘을 사용하려면 데이터가 정렬된 순서여야 한다. *이진 탐색(binary search)*은 정렬된 배열 또는 ArrayList의 중간에서 시작하여, 원하는 값을 찾거나 모든 요소가 제거될 때까지 각 재귀 호출마다 배열 또는 ArrayList의 절반을 제거한다.
    • 4.17.B.2 이진 탐색은 일반적으로 선형 탐색보다 효율적이다.
      • 제외 사항: 선형 탐색과 이진 탐색 외의 탐색 알고리즘은 AP 컴퓨터 과학 A 과정 및 시험 범위를 벗어난다.
    • 4.17.B.3 이진 탐색 알고리즘은 반복적으로나 재귀적으로 작성할 수 있다.

    학습 목표 4.17.C: 컬렉션을 정렬하기 위해 병합 정렬 알고리즘을 사용할 때의 각 반복에 대한 결과를 판단한다.

    • 4.17.C.1 *병합 정렬(merge sort)*은 배열 또는 ArrayList의 요소를 정렬하는 데 사용할 수 있는 재귀 정렬 알고리즘이다.
      • 제외 사항: 선택 정렬, 삽입 정렬 및 병합 정렬 외의 정렬 알고리즘은 AP 컴퓨터 과학 A 과정 및 시험 범위를 벗어난다.
    • 4.17.C.2 병합 정렬은 배열을 작은 서브 배열(subarray)로 반복적으로 나누어 각 서브 배열이 한 개의 요소가 될 때까지 나눈 후, 정렬된 서브 배열들을 재귀적으로 다시 합쳐 최종 정렬된 배열을 형성한다.

    출처: College Board AP Course and Exam Description

    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.

    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.

로그인 또는 계정 만들기

IGCSE, A-Level & AP