Skip to content · ⁨Lompat ke konten⁩
Subjects · ⁨Materi⁩

AP Computer Science A · ⁨AP Ilmu Komputer A⁩

Tips

AP Computer Science A adalah mata kuliah Java: objek dan kelas, tipe primitif dan alur kontrol, penulisan kelas, array dan ArrayLists, array 2D, warisan (inheritance) dan polimorfisme, serta rekursi. Ini adalah kursus pemrograman pertama yang diajarkan dengan kode berorientasi objek sungguhan, bukan pseudocode.

Keempat soal bebas respons ditulis tangan menggunakan Java. Tidak ada compiler yang akan menangkap koma yang hilang atau tipe return yang salah untuk Anda, jadi tuliskan kode di atas kertas selama masa persiapan — ini merupakan keterampilan yang berbeda dari mengetiknya.

Array dan ArrayLists adalah topik yang paling sering diuji. Menjadi mahir dalam traversal, penyisipan, dan penghapusan, serta mengetahui indeks mana yang bergeser saat Anda menghapus elemen, memberikan hasil lebih besar daripada satu jam latihan lainnya.

Catatan mencakup unit-unit CED dalam bahasa Java, dengan contoh yang dapat dijalankan dan diedit di browser. Soal FRQ masa lalu dan pedoman penilaian tersedia di perpustakaan — keempatnya adalah soal penulisan kode, sehingga jawaban yang ditunjukkan adalah metode lengkap, bukan potongan kode.

  • 1

    Using Objects and Methods · ⁨Menggunakan Benda dan Metode⁩

    Watch lesson · ⁨Tonton pelajaran⁩
    1.1

    Introduction to Algorithms, Programming, and Compilers · ⁨Pengenalan Algoritma, Pemrograman, dan Kompiler⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.1.A: Mewakili pola dan algoritma yang ditemukan dalam kehidupan sehari-hari menggunakan bahasa tulisan atau diagram.

    • 1.1.A.1 Algoritma mendefinisikan proses bertahap yang harus diikuti saat menyelesaikan tugas atau memecahkan masalah. Algoritma ini dapat direpresentasikan menggunakan bahasa tulisan atau diagram.
    • 1.1.A.2 Pengurutan menentukan urutan kapan langkah-langkah dalam suatu proses diselesaikan. Langkah-langkah dalam suatu proses diselesaikan satu per satu.

    Tujuan Pembelajaran 1.1.B: Jelaskan proses kompilasi dan eksekusi kode.

    • 1.1.B.1 Kode dapat ditulis di editor teks apa pun; namun, lingkungan pengembangan terintegrasi (IDE) sering digunakan untuk menulis program karena menyediakan alat bagi programmer untuk menulis, mengkompilasi, dan menjalankan kode.
    • 1.1.B.2 Kompiler memeriksa kode untuk beberapa kesalahan. Kesalahan yang terdeteksi oleh kompiler harus diperbaiki sebelum program dapat dijalankan.

    Tujuan Pembelajaran 1.1.C: Identifikasi jenis-jenis kesalahan pemrograman.

    • 1.1.C.1 Kesalahan sintaks adalah kesalahan dalam program di mana aturan bahasa pemrograman tidak dipatuhi. Kesalahan ini dideteksi oleh kompiler.
    • 1.1.C.2 Kesalahan logika adalah kesalahan dalam algoritma atau program yang menyebabkan program berperilaku tidak benar atau tidak terduga. Kesalahan ini dideteksi dengan menguji program dengan data khusus untuk melihat apakah program menghasilkan hasil yang diharapkan.
    • 1.1.C.3 Kesalahan waktu berjalan adalah kesalahan dalam program yang terjadi selama eksekusi program. Kesalahan waktu berjalan biasanya menyebabkan program berhenti secara tidak normal.
    • 1.1.C.4 Eksception adalah jenis kesalahan waktu berjalan yang terjadi akibat kesalahan tak terduga yang tidak terdeteksi oleh kompiler. Eksception mengganggu alur normal eksekusi program.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Kode sumber di stasiun kerja — program ditulis, dikompilasi, dan dijalankan sebagai instruksi presisi
    Kode sumber di stasiun kerja — program ditulis, dikompilasi, dan dijalankan sebagai instruksi presisi

    Algoritma adalah prosedur terbatas langkah demi langkah yang menyelesaikan masalah. Program mengekspresikan algoritma dalam bahasa yang dapat dijalankan komputer. Java dikompilasi: kompiler menerjemahkan kode sumber Anda menjadi bytecode, yang dijalankan oleh Java Virtual Machine (JVM). Kesalahan sintaks (melanggar tata bahasa) ditangkap oleh kompiler; kesalahan logika (hasil salah) tidak – program tetap berjalan tetapi berperilaku keliru.

    Sebuah kompiler menerjemahkan seluruh program sekaligus; sebuah interpreter menjalankannya baris demi baris
    Kompiler menerjemahkan seluruh program sekaligus; interpreter menjalankannya baris per baris
    Beberapa chip prosesor komputer terlihat dari bawah
    Program Java Anda dikompilasi menjadi instruksi yang sebenarnya dijalankan oleh CPU seperti salah satu di atas
    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    algorithm/ˈælɡərɪθəm/ algoritma
    program/ˈprəʊɡræm/ program
    compiled/kəmˈpaɪld/ disusun ulang
    compiler/kəmˈpaɪlə/ compiler
    syntax error/ˈsɪntæks ˈerə/ kesalahan sintaksis
    logic error/ˈlɒdʒɪk ˈerə/ kesalahan logika
    variable/ˈveərɪəbl/ pembolehubah
    1.2

    Variables and Data Types · ⁨Variabel dan Tipe Data⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.2.A: Mengidentifikasi kategori tipe data yang paling tepat untuk spesifikasi tertentu.

    • 1.2.A.1 Tipe data adalah sekumpulan nilai beserta sekumpulan operasi yang sesuai pada nilai-nilai tersebut. Tipe data dapat dikategorikan sebagai primitif atau referensi.
    • 1.2.A.2 Tipe data primitif yang digunakan dalam kursus ini mendefinisikan himpunan nilai dan operasi yang sesuai pada nilai-nilai tersebut untuk angka dan nilai Boolean.
    • 1.2.A.3 Tipe referensi digunakan untuk mendefinisikan objek yang bukan tipe primitif.

    Tujuan Pembelajaran 1.2.B: Mengembangkan kode untuk mendeklarasikan variabel guna menyimpan nilai numerik dan Boolean.

    • 1.2.B.1 Tiga tipe data primitif yang digunakan dalam kursus ini adalah int, double, dan boolean. Nilai int adalah bilangan bulat. Nilai double adalah bilangan riil. Nilai boolean dapat berupa true atau false.
      • Pernyataan Pengecualian: Lima tipe data primitif lainnya (long, short, byte, float, dan char) berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 1.2.B.2 Variabel adalah lokasi penyimpanan yang memegang nilai, yang dapat berubah selama program berjalan. Setiap variabel memiliki nama dan tipe data terkait. Variabel dari tipe primitif memegang nilai primitif dari tipe tersebut.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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:

    Bahasa Indonesia

    Variabel adalah kotak bernama yang menyimpan nilai dengan tipe tetap. Tipe primatif utama Java adalah int (bilangan bulat), double (desimal), dan boolean (true/false). Deklarasikan dengan tipe terlebih dahulu:

    Tipe data dasar Java, masing-masing menyimpan jenis nilai yang berbeda
    Tipe data dasar Java, masing-masing menyimpan jenis nilai yang berbeda
    int score = 90;
    double price = 4.99;
    boolean passed = true;
    
    Explore · ⁨Jelajahi⁩

    Explore how a variable holds one value at a time · ⁨Jelajahi bagaimana variabel menyimpan satu nilai pada satu waktu⁩

    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. · ⁨Sebuah variabel adalah kotak bernama yang menyimpan satu nilai dengan tipe tetap. Telusuri baris-barisnya dan perhatikan setiap kotak mengambil nilainya; perhatikan bahwa penugasan ulang score menimpa angka lama alih-alih membuat kotak baru.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    type/taɪp/ tipografi
    primitive types/ˈprɪmɪtɪv taɪps/ tipe primitif
    expression/ekˈspreʃn/ ekspresi
    modulus/ˈmɒdjʊləs/ modulus
    escape sequence/eˈskeɪp ˈsiːkwəns/ urutan escape
    assignment/əˈsaɪnmənt/ penugasan
    Casting/ˈkæstɪŋ/ Casting
    library/ˈlaɪbrəri/ perpustakaan
    abstraction/əbˈstrækʃn/ abstraksi
    Comments/ˈkɒments/ Komentar
    method signature/ˈmeθəd ˈsɪɡnɪtʃə/ tanda tangan metode
    arguments/ˈɑːɡjuːmənts/ argumen
    class (static) method/klæs ˈmeθəd/ metode kelas (statis)
    1.3

    Expressions and Output · ⁨Ekspresi dan Output⁩

    Syllabus · ⁨Silabus⁩
    English

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

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

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

    Tujuan Pembelajaran 1.3.A: Mengembangkan kode untuk menghasilkan output dan menentukan hasil yang akan ditampilkan.

    • 1.3.A.1 System.out.print dan System.out.println menampilkan informasi pada layar komputer. System.out.println memindahkan kursor ke baris baru setelah informasi ditampilkan, sedangkan System.out.print tidak.

    Tujuan Pembelajaran 1.3.B: Mengembangkan kode untuk memanfaatkan literal string dan menentukan hasil penggunaan literal string.

    • 1.3.B.1 Literal adalah representasi kode dari nilai tetap.
    • 1.3.B.2 Literal string adalah urutan karakter yang dibatasi oleh tanda kutip ganda.
    • 1.3.B.3 Urutan escape adalah urutan khusus karakter yang dapat dimasukkan ke dalam string. Mereka dimulai dengan \ dan memiliki arti khusus dalam Java. Urutan escape yang digunakan dalam kursus ini meliputi tanda kutip ganda \", garis miring terbalik \\, dan baris baru \n.

    Tujuan Pembelajaran 1.3.C: Mengembangkan kode untuk ekspresi aritmatika dan menentukan hasil dari ekspresi-ekspresi ini.

    • 1.3.C.1 Ekspresi aritmatika, yang terdiri dari nilai numerik, variabel, dan operator, mencakup ekspresi bertipe int dan double.
    • 1.3.C.2 Operator aritmatika terdiri dari penjumlahan +, pengurangan -, perkalian *, pembagian /, dan sisa bagian %. Operasi aritmatika yang menggunakan dua nilai int akan mengevaluasi menjadi nilai int. Operasi aritmatika yang menggunakan setidaknya satu nilai double akan mengevaluasi menjadi nilai double.
      • Pernyataan Pengecualian: Ekspresi yang menghasilkan nilai double khusus (misalnya tak hingga dan NaN) berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 1.3.C.3 Ketika membagi nilai numerik yang keduanya int, hasilnya hanyalah bagian bilangan bulat dari hasil bagi. Ketika membagi nilai numerik yang menggunakan setidaknya satu double, hasilnya adalah hasil bagi.
    • 1.3.C.4 Operator sisa % digunakan untuk menghitung sisa ketika satu angka a dibagi oleh angka lain b.
      • Pernyataan pengecualian: Penggunaan nilai kurang dari 0 untuk a dan penggunaan nilai kurang dari atau sama dengan 0 untuk b berada di luar cakupan mata kuliah dan ujian AP Computer Science A.
    • 1.3.C.5 Operator dapat digunakan untuk menyusun ekspresi majemuk. Pada waktu kompilasi, nilai numerik dikaitkan dengan operator sesuai dengan prioritas operator untuk menentukan bagaimana pengelompokannya. Kurung dapat digunakan untuk memodifikasi prioritas operator. Perkalian, pembagian, dan sisa memiliki prioritas lebih tinggi daripada penjumlahan dan pengurangan. Operator dengan prioritas yang sama dievaluasi dari kiri ke kanan.
    • 1.3.C.6 Upaya untuk membagi bilangan bulat dengan bilangan bulat nol akan menghasilkan ArithmeticException.
      • Pernyataan pengecualian: Penggunaan pembagian dengan nol ketika satu nilai numerik adalah double berada di luar cakupan mata kuliah dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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".

    Bahasa Indonesia

    Ekspresi menggabungkan nilai dan operator untuk menghitung hasil: + - * / dan % (modulo, sisa bagi). Pembagian bilangan bulat memotong desimal: 7 / 2 adalah 3, sementara 7 % 2 adalah 1. Precedensi operator mengikuti aturan matematika (*,/,% didahulukan sebelum +,-). Cetak dengan:

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

    Membagi bilangan bulat dengan bilangan bulat 0 (seperti 7 / 0) tidak diperbolehkan dan menyebabkan error saat runtime dengan ArithmeticException. Di dalam string, tanda backslash menandai baris escape: \" mencetak tanda kutip ganda, \\ satu backslash tunggal, dan \n memulai baris baru – sehingga System.out.println("She said \"hi\""); mencetak She said "hi".

    Explore · ⁨Jelajahi⁩

    Explore the order of operations step by step · ⁨Jelajahi urutan operasi langkah demi langkah⁩

    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. · ⁨Java menerapkan *, /, % sebelum + dan -, bekerja dari kiri ke kanan. Perhatikan setiap langkah dan lihat mengapa 2 + 3 * 4 bernilai $14$, bukan $20$ — perkalian dilakukan terlebih dahulu.⁩

    1.4

    Assignment Statements and Input · ⁨Pernyataan Alokasi dan Input⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.4.A: Mengembangkan kode untuk pernyataan penugasan dengan ekspresi dan menentukan nilai yang disimpan dalam variabel sebagai hasil dari pernyataan tersebut.

    • 1.4.A.1 Setiap variabel harus diberi nilai sebelum dapat digunakan dalam sebuah ekspresi. Nilai tersebut harus berasal dari tipe data yang kompatibel. Variabel diinisialisasi pertama kali saat diberi nilai. Tipe referensi dapat diberikan objek baru atau null jika tidak ada objek. Literal null adalah nilai khusus yang digunakan untuk menunjukkan bahwa referensi tidak terkait dengan objek apa pun.
    • 1.4.A.2 Operator penugasan = memungkinkan program untuk menginisialisasi atau mengubah nilai yang disimpan dalam variabel. Nilai dari ekspresi di sebelah kanan disimpan dalam variabel di sebelah kiri.
      • Pernyataan pengecualian: Penggunaan operator penugasan di dalam ekspresi (misalnya, a = b = 4; atau a[i += 5]) berada di luar cakupan mata kuliah dan ujian AP Computer Science A.
    • 1.4.A.3 Selama eksekusi, sebuah ekspresi dievaluasi untuk menghasilkan satu nilai. Nilai dari sebuah ekspresi memiliki tipe berdasarkan evaluasi ekspresi tersebut.

    Tujuan Pembelajaran 1.4.B: Mengembangkan kode untuk membaca masukan.

    • 1.4.B.1 Masukan dapat datang dalam berbagai bentuk, seperti taktil, audio, visual, atau teks. Kelas Scanner adalah salah satu cara untuk mendapatkan teks masukan dari keyboard.
      • Pernyataan pengecualian: Bentuk masukan spesifik apa pun dari pengguna berada di luar cakupan mata kuliah dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

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

    Bahasa Indonesia

    Alokasi x = expr; mengevaluasi sisi kanan dan menyimpannya ke variabel kiri. Baca input menggunakan Scanner:

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

    Casting and Range of Variables · ⁨Casting dan Rentang Variabel⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.5.A: Mengembangkan kode untuk melakukan casting pada nilai primitif ke tipe primitif berbeda dalam ekspresi aritmatika dan menentukan nilai yang dihasilkan sebagai akibatnya.

    • 1.5.A.1 Operator casting (int) dan (double) dapat digunakan untuk mengonversi dari nilai double ke nilai int (atau sebaliknya).
    • 1.5.A.2 Melakukan casting pada nilai double ke nilai int menyebabkan digit-digit di sebelah kanan koma desimal dipotong.
    • 1.5.A.3 Beberapa kode menyebabkan nilai int secara otomatis dikast (diperluas) menjadi nilai double.
    • 1.5.A.4 Nilai bertipe double dapat dibulatkan ke bilangan bulat terdekat oleh (int)(x + 0.5) untuk bilangan non-negatif atau (int)(x - 0.5) untuk bilangan negatif.

    Tujuan Pembelajaran 1.5.B: Mendeskripsikan kondisi ketika ekspresi bilangan bulat mengevaluasi ke nilai di luar rentang.

    • 1.5.B.1 Konstanta Integer.MAX_VALUE menyimpan nilai terbesar yang mungkin dari nilai int. Konstanta Integer.MIN_VALUE menyimpan nilai terkecil yang mungkin dari nilai int.
    • 1.5.B.2 Nilai bilangan bulat dalam Java direpresentasikan oleh nilai bertipe int, yang disimpan menggunakan jumlah memori terbatas (4 byte). Oleh karena itu, nilai int harus berada dalam rentang dari Integer.MIN_VALUE hingga Integer.MAX_VALUE termasuk.
    • 1.5.B.3 Jika sebuah ekspresi akan mengevaluasi ke nilai int di luar rentang yang diperbolehkan, terjadi overflow bilangan bulat. Hasilnya adalah nilai int dalam rentang yang diperbolehkan tetapi tidak necessarily merupakan nilai yang diharapkan.

    Tujuan Pembelajaran 1.5.C: Mendeskripsikan kondisi yang membatasi akurasi ekspresi.

    • 1.5.C.1 Komputer mengalokasikan jumlah memori tertentu untuk menyimpan data berdasarkan tipe data. Jika sebuah ekspresi akan mengevaluasi ke double yang lebih presisi daripada yang dapat disimpan dalam jumlah memori yang dialokasikan, terjadi kesalahan pembulatan. Hasilnya akan dibulatkan ke nilai yang dapat direpresentasikan. Untuk menghindari kesalahan pembulatan yang terjadi secara alami, gunakan nilai int.
      • Pernyataan pengecualian: Tipe data desimal khusus lainnya yang dapat digunakan untuk menghindari kesalahan pembulatan berada di luar cakupan mata kuliah dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Rentang int, overflow dan truncation

    Setiap tipe memiliki rentang tetap; sebuah int akan meluber (overflow) melewati sekitar 2.1 miliar. Pencastan mengubah antar tipe. Pelebaran (int ke double) dilakukan otomatis; penyempitan memerlukan pencastan eksplisit, yang memotong (tidak membulatkan):

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

    Kemampuan ujian: waspadai pembagian bilangan bulat yang menghasilkan hasil terpotong saat desimal diharapkan – cast satu operand ke double terlebih dahulu.

    Contoh terarah. Jejakkan setiap ekspresi:

    • 7 / 2 → 3 (keduanya int, jadi pembagian dipotong);
    • 7.0 / 2 → 3.5 (satu double memaksa pembagian riil);
    • 7 % 2 → 1 (sisa baginya)
    • (double) 7 / 2 → 3.5 (penyimpanan tipe mengikat lebih ketat daripada /, sehingga menjadi 7.0 / 2);
    • (double) (7 / 2) → 3.0 (tanda kurung menghitung 7 / 2 = 3 dalam int pertama, kemudian memperlebar).

    Dua terakhir terlihat mirip tetapi berbeda – posisi penyimpanan tipe menentukan apakah pemotongan terjadi.

    Explore · ⁨Jelajahi⁩

    Why int and double store numbers differently · ⁨Mengapa int dan double menyimpan angka berbeda⁩

    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. · ⁨Sebuah int hanya menyimpan bilangan bulat dalam rentang tetap; sebuah double menyimpan mantissa dan eksponen, menukar ketepatan untuk rentang yang sangat besar. Mengonversi double→int membuang pecahan, dan nilai melampaui rentang int akan menyebabkan overflow.⁩

    1.6

    Compound Assignment Operators · ⁨Operator Penugasan Majemuk⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.6.A: Mengembangkan kode untuk pernyataan penugasan dengan operator penugasan majemuk dan menentukan nilai yang disimpan dalam variabel sebagai akibatnya.

    • 1.6.A.1 Operator penugasan majemuk +=, -=, *=, /=, dan %= dapat digunakan sebagai pengganti operator penugasan dalam ekspresi numerik. Operator penugasan majemuk melakukan operasi aritmatika yang ditunjukkan antara nilai di sebelah kiri dan nilai di sebelah kanan, lalu menetapkan hasilnya ke variabel di sebelah kiri.
    • 1.6.A.2 Operator post-increment ++ dan operator post-decrement -- digunakan untuk menambahkan 1 atau mengurangi 1 dari nilai yang disimpan dalam variabel numerik. Nilai baru ditetapkan ke variabel.
      • Pernyataan Pengecualian: Penggunaan operator increment dan decrement dalam bentuk prefiks (misalnya, ++x) berada di luar cakupan kursus dan ujian AP Computer Science A. Penggunaan operator increment dan decrement di dalam ekspresi lain (misalnya, arr[x++]) berada di luar cakupan kursus dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

    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.

    Bahasa Indonesia

    Penulisan singkat menggabungkan operasi dengan penugasan: x += 5 berarti x = x + 5; demikian pula -=, *=, /=, %=. Operator increment dan decrement x++ dan x-- menambah atau mengurangi satu.

    1.7

    Application Program Interface (API) and Libraries · ⁨Application Program Interface (API) dan Pustaka⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.7.A: Mengidentifikasi atribut dan perilaku kelas yang ditemukan dalam pustaka yang terkandung dalam API.

    • 1.7.A.1 Pustaka adalah kumpulan kelas. Spesifikasi application programming interface (API) memberi tahu programmer cara menggunakan kelas-kelas tersebut. Dokumentasi yang ditemukan dalam spesifikasi API dan pustaka sangat penting untuk memahami atribut dan perilaku kelas yang didefinisikan oleh API. Sebuah kelas mendefinisikan tipe referensi tertentu. Kelas dalam API dan pustaka dikelompokkan ke dalam paket. Kelas dan pustaka kelas yang sudah ada dapat digunakan untuk membuat objek.
    • 1.7.A.2 Atribut merujuk pada data yang terkait dengan kelas dan disimpan dalam variabel. Perilaku merujuk pada apa yang dapat dilakukan oleh instance dari kelas tersebut (atau apa yang dapat dilakukan dengannya) dan didefinisikan oleh metode.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 抽象.

    Bahasa Indonesia

    Sebuah API (Application Programming Interface) adalah daftar kelas dan metode yang dipublikasikan yang dapat Anda gunakan. Sebuah pustaka adalah kumpulan kelas siap pakai (seperti Math, String, Scanner). Anda membaca dokumentasi API untuk mempelajari apa yang dibutuhkan sebuah metode (parameternya) dan dikembalikan, tanpa melihat kode dalamnya – contoh dari abstraksi.

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Interface/ˈɪntəfeɪs/ Antarmuka
    1.8

    Documentation with Comments · ⁨Dokumentasi dengan Komentar⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.8.A: Mendeskripsikan fungsionalitas dan penggunaan kode melalui komentar.

    • 1.8.A.1 Komentar ditulis baik untuk programmer asli maupun programmer lain agar dapat memahami kode dan fungsionalitasnya, tetapi diabaikan oleh compiler dan tidak dieksekusi saat program dijalankan. Tiga jenis komentar dalam Java meliputi /* */, yang menghasilkan blok komentar; //, yang menghasilkan komentar pada satu baris; dan /** */, yang merupakan komentar Javadoc dan digunakan untuk membuat dokumentasi API.
    • 1.8.A.2 Prasyarat adalah kondisi yang harus benar tepat sebelum eksekusi sebuah metode agar dapat berperilaku sesuai harapan. Tidak ada ekspektasi bahwa metode akan memeriksa apakah prasyarat terpenuhi.
    • 1.8.A.3 Pasca-syarat adalah kondisi yang harus selalu benar setelah eksekusi sebuah metode. Pasca-syarat menggambarkan hasil eksekusi dalam hal apa yang dikembalikan atau nilai saat ini dari atribut suatu objek.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Komentar diabaikan oleh compiler tetapi menjelaskan kode kepada manusia: // untuk satu baris, /* ... */ untuk blok, dan /** ... */ untuk komentar Javadoc yang mendokumentasikan tujuan, parameter, dan nilai pengembalian sebuah metode. Prasyarat dan pasca-syarat yang presisi ditulis di sini.

    1.9

    Method Signatures · ⁨Tanda Tangan Metode⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.9.A: Mengidentifikasi metode yang benar untuk dipanggil berdasarkan dokumentasi dan tanda tangan metode.

    • 1.9.A.1 Sebuah metode adalah blok kode bernama yang hanya berjalan ketika dipanggil. Sebuah blok kode adalah bagian kode apa pun yang dibungkus dalam kurung kurawal. Abstraksi prosedural memungkinkan seorang programmer menggunakan sebuah metode dengan mengetahui apa yang dilakukan metode tersebut meskipun mereka tidak tahu bagaimana metode tersebut ditulis.
    • 1.9.A.2 Sebuah parameter adalah variabel yang dideklarasikan dalam header metode atau konstruktor dan dapat digunakan di dalam tubuh metode. Hal ini memungkinkan nilai atau argumen untuk dikirim dan digunakan oleh metode atau konstruktor. Tanda tangan metode untuk sebuah metode dengan parameter terdiri dari nama metode dan daftar berurutan tipe parameter. Tanda tangan metode untuk sebuah metode tanpa parameter terdiri dari nama metode dan daftar parameter kosong.

    Tujuan Pembelajaran 1.9.B: Mendeskripsikan cara memanggil metode.

    • 1.9.B.1 Sebuah metode void tidak memiliki nilai pengembalian dan oleh karena itu tidak dipanggil sebagai bagian dari ekspresi.
    • 1.9.B.2 Sebuah metode non-void mengembalikan nilai yang sama tipenya dengan tipe pengembalian di header. Untuk menggunakan nilai pengembalian saat memanggil metode non-void, nilai tersebut harus disimpan dalam variabel atau digunakan sebagai bagian dari ekspresi.
    • 1.9.B.3 Sebuah argumen adalah nilai yang dikirim ke dalam sebuah metode saat metode tersebut dipanggil. Argumen yang dikirim ke sebuah metode harus kompatibel dalam jumlah dan urutan dengan tipe yang diidentifikasi dalam daftar parameter tanda tangan metode. Saat memanggil metode, argumen dikirim menggunakan call by value. Call by value menginisialisasi parameter dengan salinan argumen.
    • 1.9.B.4 Metode dikatakan overloaded (terbeban) ketika terdapat beberapa metode dengan nama yang sama tetapi berbeda tanda tangannya.
    • 1.9.B.5 Sebuah pemanggilan metode mengganggu eksekusi sekuensial pernyataan, menyebabkan program untuk pertama kali mengeksekusi pernyataan-pernyataan di dalam metode sebelum melanjutkan. Setelah pernyataan terakhir dalam metode dieksekusi atau pernyataan return dieksekusi, alur kendali dikembalikan ke titik tepat di mana pemanggilan metode dilakukan.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Sebuah tanda tangan metode adalah nama metode beserta jenis parameternya, mis. nextInt() atau substring(int, int). Untuk memanggil sebuah metode, Anda harus menyediakan argumen yang sesuai dengan parameternya dalam jumlah, jenis, dan urutan. Header metode (deklarasi lengkap) juga menyatakan jenis pengembalian – jenis nilai yang dikembalikan metode (void jika tidak ada) – tetapi jenis pengembalian bukan bagian dari tanda tangan, itulah sebabnya dua metode tidak dapat berbeda hanya oleh jenis pengembalian.

    1.10

    Calling Class Methods · ⁨Memanggil Metode Kelas⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.10.A: Mengembangkan kode untuk memanggil metode kelas dan menentukan hasil dari pemanggilan tersebut.

    • 1.10.A.1 Metode kelas terkait dengan kelas, bukan instansinya. Metode kelas mencakup kata kunci static dalam header sebelum nama metode.
    • 1.10.A.2 Metode kelas biasanya dipanggil menggunakan nama kelas bersama dengan operator titik. Ketika pemanggilan metode terjadi di dalam kelas yang mendefinisikannya, penggunaan nama kelas adalah opsional dalam pemanggilan.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Sebuah metode kelas (statis) milik kelas itu sendiri, sehingga Anda memanggilnya pada nama kelas: ClassName.method(args). Tidak perlu objek.

    Explore · ⁨Jelajahi⁩

    Follow a class-method call on the stack · ⁨Ikuti pemanggilan metode kelas pada tumpukan (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. · ⁨Memanggil metode kelas seperti Math.max mendorong bingkai baru ke tumpukan panggilan; ketika metode mengembalikan nilai, bingkainya dilepas dan kendali kembali ke Caller. Telusuri untuk melihat tumpukan membesar dan mengecil.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    class/klæs/ kelas
    1.11

    Math Class · ⁨Kelas Math⁩

    Syllabus · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 1.11.A: Mengembangkan kode untuk menulis ekspresi yang menyertakan pemanggilan ke perpustakaan matematika bawaan dan menentukan nilai yang dihasilkan sebagai akibatnya.

    • 1.11.A.1 Kelas Math merupakan bagian dari paket java.lang. Kelas-kelas dalam paket java.lang tersedia secara default.
    • 1.11.A.2 Kelas Math hanya berisi metode kelas. Berikut ini Math metode kelas—termasuk fungsinya dan kapan digunakan—merupakan bagian dari Rujukan Cepat Java:
      • static int abs(int x) mengembalikan nilai mutlak dari nilai int.
      • static double abs(double x) mengembalikan nilai mutlak dari nilai double.
      • static double pow(double base, double exponent) mengembalikan nilai parameter pertama yang dipangkatkan dengan parameter kedua.
      • static double sqrt(double x) mengembalikan akar kuadrat nonnegatif dari nilai double.
      • static double random() mengembalikan nilai double yang lebih besar atau sama dengan 0.0 dan kurang dari 1.0.
    • 1.11.A.3 Nilai-nilai yang dikembalikan dari Math.random() dapat dimanipulasi menggunakan operator aritmatika dan pemetaan (casting) untuk menghasilkan bilangan acak int atau double dalam rentang tertentu berdasarkan kriteria yang ditentukan. Setiap ujung rentang dapat bersifat inklusif, artinya nilai tersebut termasuk, atau eksklusif, artinya nilai tersebut tidak termasuk.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

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

    Bahasa Indonesia

    Kelas Math menyediakan metode matematika statis: Math.abs(x), Math.pow(base, exp), Math.sqrt(x), dan Math.random() (sebuah double dalam $[0,1)$). Untuk mendapatkan bilangan bulat acak dari 0 hingga n-1: (int)(Math.random() * n).

    1.12

    Objects: Instances of Classes · ⁨Objek: Instansi Kelas⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.12.A: Menjelaskan hubungan antara kelas dan objek.

    • 1.12.A.1 Sebuah objek adalah instans spesifik dari sebuah kelas dengan atribut yang didefinisikan. Sebuah kelas adalah implementasi formal, atau cetak biru, dari atribut dan perilaku objek.
    • 1.12.A.2 Hierarki kelas dapat dikembangkan dengan menempatkan atribut dan perilaku umum dari kelas-kelas yang berkaitan ke dalam satu kelas yang disebut superclass. Kelas-kelas yang memperluas superclass, yang disebut subclasses, dapat memanfaatkan atribut dan perilaku yang sudah ada dari superclass tanpa menggantinya dalam kode. Hal ini menciptakan hubungan pewarisan dari subclass menuju superclass.
      • Pernyataan pengecualian: Merancang dan mengimplementasikan hubungan pewarisan berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 1.12.A.3 Semua kelas dalam Java adalah subclass dari kelas Object.

    Tujuan Pembelajaran 1.12.B: Mengembangkan kode untuk mendeklarasikan variabel guna menyimpan tipe referensi.

    • 1.12.B.1 Variabel dari tipe referensi memegang referensi objek, yang dapat dipandang sebagai alamat memori dari objek tersebut.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.)

    Bahasa Indonesia
    = menyalin referensi, bukan objek

    Sebuah kelas adalah cetak biru; sebuah objek adalah instansi konkret yang dibangun darinya. Sebuah kelas mengemas data (lapang) dengan perilaku (metode) – inti dari pemrograman berorientasi objek. String, Scanner, dan ArrayList adalah semua kelas yang Anda instansiasi.

    Kelas dapat diorganisir ke dalam hierarki. Sebuah superclass memegang atribut dan perilaku yang dibagikan oleh beberapa subclass yang extend – hubungan pewarisan. Setiap kelas dalam Java pada akhirnya adalah subclass dari kelas bawaan Object, yang mengapa setiap objek sudah memiliki metode toString; menulis metode subclass dengan tanda tangan yang sama seperti superclass adalah penggantian metode. (Merancang pewarisan Anda sendiri berada di luar kursus ini, tetapi Anda diharapkan mengenali kosakata ini.)

    Diagram kelas: atribut privat dan publik metode
    Diagram kelas: atribut privat dan publik metode
    Kelas adalah cetak biru; setiap objek adalah satu instansi dibangun darinya
    Kelas adalah cetak biru; setiap objek adalah satu instansi dibangun darinya
    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    object/ˈɒbdʒekt/ benda itu sendiri
    superclass/ˈsuːpəklæs/ superclass
    subclasses/ˈsʌbklæsɪz/ subkelas
    inheritance relationship/ɪnˈherɪtəns rɪˈleɪʃənʃɪp/ hubungan pewarisan
    method overriding/ˈmeθəd ˌəʊvəˈraɪdɪŋ/ penimpaan metode
    Instantiation/ˌɪnstænʃɪˈeɪʃn/ Instantiasi
    constructor/kənˈstrʌktə/ konstruktor
    reference/ˈrefrəns/ referensi
    1.13

    Object Creation and Storage (Instantiation) · ⁨Pembuatan Objek dan Penyimpanan (Instansiasi)⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.13.A: Mengidentifikasi, menggunakan tandanya, konstruktor mana yang benar sedang dipanggil.

    • 1.13.A.1 Sebuah kelas memiliki konstruktor yang dipanggil untuk membuat objek. Mereka memiliki nama yang sama dengan kelasnya.
    • 1.13.A.2 Tanda konstruktor terdiri dari nama konstruktor, yang sama dengan nama kelas, dan daftar berurutan dari tipe parameternya. Daftar parameter, dalam header konstruktor, mencantumkan tipe dari nilai-nilai yang diluluskan dan nama variabel mereka.
    • 1.13.A.3 Konstruktor dikatakan tumpang tindih (overloaded) ketika terdapat beberapa konstruktor dengan tanda yang berbeda.

    Tujuan Pembelajaran 1.13.B: Mengembangkan kode untuk mendeklarasikan variabel dengan tipe yang tepat untuk menampung referensi objek.

    • 1.13.B.1 Variabel dari tipe referensi memegang referensi objek atau, jika tidak ada objek, null.

    Tujuan Pembelajaran 1.13.C: Mengembangkan kode untuk membuat objek dengan memanggil konstruktor.

    • 1.13.C.1 Objek biasanya dibuat menggunakan kata kunci new diikuti dengan pemanggilan ke salah satu konstruktor kelas.
    • 1.13.C.2 Parameter memungkinkan konstruktor menerima nilai untuk menetapkan nilai awal dari atribut objek.
    • 1.13.C.3 Argumen konstruktor adalah nilai yang diluluskan ke dalam konstruktor ketika konstruktor dipanggil. Argumen-argumen yang diluluskan ke konstruktor harus kompatibel baik secara urutan maupun jumlah dengan tipe-tipe yang teridentifikasi dalam daftar parameter pada tanda konstruktor. Saat memanggil konstruktor, argumen diluluskan menggunakan call by value. Call by value menginisialisasi parameter dengan salinan argumen.
    • 1.13.C.4 Pemanggilan konstruktor menghentikan eksekusi pernyataan secara berurutan, menyebabkan program terlebih dahulu mengeksekusi pernyataan-pernyataan dalam konstruktor sebelum melanjutkan. Setelah pernyataan terakhir dalam konstruktor dieksekusi, alur kendali dikembalikan ke titik segera setelah tempat konstruktor tersebut dipanggil.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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).

    Bahasa Indonesia

    Instansiasi membuat objek dengan kata kunci new, yang memanggil konstruktor:

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

    Variabel tersebut memegang referensi (alamat objek), bukan objek itu sendiri. Dua referensi dapat menunjuk ke sama objek; membandingkan mereka dengan == membandingkan alamat, bukan isi.

    Referensi juga dapat menunjuk ke sesuatu yang kosong: nilai khusus null berarti "tidak terikat pada objek apa pun". Memanggil metode pada referensi null menyebabkan crash saat waktu berjalan dengan NullPointerException. Lindungi terhadapnya dengan menguji dengan ==/!= dan memeriksa null pertama, agar && pendek-circuit sebelum metode berjalan: if (s != null && s.length() > 0).

    Variabel primitif memegang nilainya langsung, referensi memegang panah ke objek
    Variabel primitif memegang nilainya langsung, referensi memegang panah ke objek
    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    null/nʌl/ null
    instance method/ˈɪnstəns ˈmeθəd/ metode instans
    immutable/ɪˈmjuːtəbl/ tidak dapat diubah
    1.14

    Calling Instance Methods · ⁨Memanggil Metode Instance⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 1.14.A: Mengembangkan kode untuk memanggil metode instans dan menentukan hasil dari pemanggilan-pemanggilan ini.

    • 1.14.A.1 Metode instans dipanggil pada objek dari kelas tersebut. Operator titik digunakan bersama dengan nama objek untuk memanggil metode instans.
    • 1.14.A.2 Pemanggilan metode pada referensi null akan menghasilkan NullPointerException.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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().

    Bahasa Indonesia

    Sebuah metode instance bertindak pada objek tertentu, sehingga Anda memanggilnya pada referensi objek: object.method(args). Contoh: in.nextInt(), word.length().

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    instance/ˈɪnstəns/ instansi
    object-oriented programming/ˈɒbdʒekt ˈɔːrɪəntɪd ˈprəʊɡræmɪŋ/ pemrograman berorientasi objek
    1.15

    String Manipulation · ⁨Manipulasi String⁩

    Syllabus · ⁨Silabus⁩
    English

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

    Learning Objective 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).
    Bahasa Indonesia

    Tujuan Pembelajaran 1.15.A: Mengembangkan kode untuk membuat objek string dan menentukan hasil dari pembuatan dan penggabungan string.

    • 1.15.A.1 Objek String merepresentasikan urutan karakter dan dapat dibuat dengan menggunakan literal string atau dengan memanggil konstruktor kelas String.
    • 1.15.A.2 Kelas String merupakan bagian dari paket java.lang. Kelas-kelas dalam paket java.lang tersedia secara default.
    • 1.15.A.3 Objek String bersifat tidak dapat diubah (immutable), artinya setelah objek String dibuat, atributnya tidak dapat diubah lagi. Metode yang dipanggil pada objek String tidak mengubah isi dari objek String tersebut.
    • 1.15.A.4 Dua objek String dapat digabungkan atau disatukan menggunakan operator + atau +=, menghasilkan objek String baru. Nilai primitif dapat digabungkan dengan objek String. Hal ini menyebabkan konversi implisit nilai primitif menjadi objek String.
    • 1.15.A.5 Objek String dapat digabungkan dengan objek apa pun, yang secara implisit memanggil metode toString dari objek tersebut (sifat yang dijamin ada karena hubungan pewarisan yang dimiliki setiap kelas terhadap kelas Object). Metode toString dari sebuah objek mengembalikan nilai string yang mewakili objek tersebut. Subkelas dari Object sering menimpa (override) metode toString dengan implementasi khusus kelas. Penimpangan metode terjadi ketika metode publik dalam subkelas memiliki tanda tangan metode yang sama dengan metode publik dalam superclass, tetapi perilaku metode tersebut spesifik untuk subkelas.
      • Pernyataan pengecualian: Menimpa metode toString dari sebuah kelas berada di luar cakupan kursus dan ujian AP Computer Science A.

    Tujuan Pembelajaran 1.15.B: Mengembangkan kode untuk memanggil metode pada objek string dan menentukan hasil dari pemanggilan metode-metode tersebut.

    • 1.15.B.1 Sebuah objek String memiliki nilai indeks mulai dari 0 hingga satu kurang dari panjang string. Mencoba mengakses indeks di luar rentang ini akan menghasilkan StringIndexOutOfBoundsException.
    • 1.15.B.2 Metode-metode String berikut—termasuk fungsi dan penggunaannya—merupakan bagian dari Rujukan Cepat Java:
      • int length() mengembalikan jumlah karakter dalam sebuah objek String.
      • String substring(int from, int to) mengembalikan substrings yang dimulai dari indeks from dan berakhir pada indeks to - 1.
      • String substring(int from) mengembalikan substring(from, length()).
      • int indexOf(String str) mengembalikan indeks kemunculan pertama dari str; mengembalikan -1 jika tidak ditemukan.
      • boolean equals(Object other) mengembalikan true jika this sesuai dengan urutan karakter yang sama dengan other; mengembalikan false jika tidak.
      • int compareTo(String other) mengembalikan nilai < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 jika this lebih besar dari other. String diurutkan berdasarkan abjad.
      • Pernyataan pengecualian: Menggunakan metode equals untuk membandingkan satu objek String dengan objek bertipe lain selain String berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 1.15.B.3 String yang identik dengan substring elemen tunggal pada posisi index dapat dibuat dengan memanggil substring(index, index + 1).

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    String bersifat tak berubah

    Objek String tak berubah – metode mengembalikan string baru alih-alih mengubah yang asli. Metode utama (semua indeks dimulai dari 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
    

    Keterampilan ujian: substring(a, b) mencakup indeks a tetapi mengecualikan b, dan perbandingan String harus menggunakan .equals, bukan == – dua jebakan String yang paling sering diujikan.

    Contoh terpecahkan. Misalkan String s = "COMPUTER"; (indeks 0–7). Maka s.length() adalah 8; s.substring(0, 4) adalah "COMP" (indeks 0,1,2,3 – indeks 4 dikecualikan); s.substring(4) adalah "UTER" (dari indeks 4 hingga akhir); s.indexOf("PU") adalah 3; dan s.indexOf("X") adalah -1 (tidak ditemukan). Menghitung ujung yang dikecualikan dari substring adalah kesalahan tunggal yang paling umum.

    Meminta indeks di luar 0 hingga length()-1 (argumen substring atau charAt yang buruk, mis. s.substring(0, 20) di sini) menyebabkan crash dengan StringIndexOutOfBoundsException – sepupu String dari error indeks array.

    Indeks string dimulai dari 0
    Indeks string dimulai dari 0
    Explore · ⁨Jelajahi⁩

    Explore string indices and slicing · ⁨Jelajahi indeks string dan pemotongan (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. · ⁨Setiap karakter memiliki indeks, dan pengnomoran dimulai dari 0. Seret awal dan akhir untuk melihat bagaimana substring(from, to) mengambil karakter dari from hingga — tetapi tidak termasuk — to.⁩

    1.15

    Exam tips · ⁨Tips ujian⁩

    English
    • 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.
    Bahasa Indonesia
    • Jejakkan kode secara manual baris demi baris, melacak nilai setiap variabel dalam tabel – ujian menghargai pelacakan teliti dibandingkan menebak.
    • Kenali tipe primitif Java dan bahwa pembagian bilangan bulat memotong ($7/2$ memberikan $3$); gunakan penyimpanan tipe atau double untuk pembagian sebenarnya.
    • Bedakan kesalahan compile-time (sintaks, tipe) dari kesalahan run-time – pahami yang bernama: ArithmeticException (int ÷ 0), NullPointerException (metode pada referensi null), StringIndexOutOfBoundsException / ArrayIndexOutOfBoundsException – dan kesalahan logika (output salah).
    • Ikuti urutan prioritas operator dan inisialisasi setiap variabel sebelum Anda menggunakannya.
    • Pada soal uraian, tuliskan Java lengkap, dapat dikompilasi – kembalikan tipe yang benar dan sesuaikan dengan header metode secara presisi.
  • 2

    Selection and Iteration · ⁨Seleksi dan Iterasi⁩

    Watch lesson · ⁨Tonton pelajaran⁩
    2.1

    Selection and Repetition in Algorithms · ⁨Seleksi dan Pengulangan dalam Algoritma⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.1.A: Merepresentasikan pola dan algoritma yang melibatkan seleksi dan pengulangan yang ditemukan dalam kehidupan sehari-hari menggunakan bahasa tertulis atau diagram.

    • 2.1.A.1 Blok pembangun algoritma mencakup penelusuran, seleksi, dan pengulangan.
    • 2.1.A.2 Algoritma dapat mengandung seleksi, melalui pengambilan keputusan, dan pengulangan, melalui perulangan.
    • 2.1.A.3 Seleksi terjadi ketika pilihan tentang bagaimana eksekusi algoritma akan berlanjut didasarkan pada keputusan true atau false.
    • 2.1.A.4 Pengulangan adalah ketika suatu proses berulang hingga hasil yang diinginkan tercapai.
    • 2.1.A.5 Urutan di mana penelusuran, seleksi, dan pengulangan digunakan berkontribusi terhadap hasil algoritma.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Diagram alir dengan berlian keputusan: seleksi memilih jalur mana yang diambil algoritma
    Diagram alir dengan berlian keputusan: seleksi memilih jalur mana yang diambil algoritma

    Algoritma dibangun dari tiga struktur kendali: urutan (langkah-langkah berurutan), seleksi (memilih jalur), dan iterasi (mengulang langkah). Topik ini mencakup seleksi dan iterasi – alat yang memungkinkan program membuat keputusan dan melakukan perulangan.

    Tiga struktur kendali: urutan, seleksi, dan iterasi
    Tiga struktur kendali: urutan, seleksi, dan iterasi
    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    control structures/kənˈtrəʊl ˈstrʌktʃəz/ struktur kontrol
    selection/sɪˈlekʃn/ pemilihan
    iteration/ˌɪtəˈreɪʃn/ iterasi
    boolean expression/ˈbuːlɪən ekˈspreʃn/ ekspresi boolean
    relational operators/rɪˈleɪʃənl ˈɒpəreɪtəz/ operator relasional
    if statement/ɪf ˈsteɪtmənt/ pernyataan if
    Logical operators/ˈlɒdʒɪkl ˈɒpəreɪtəz/ Operator logika
    short-circuit evaluation/ʃɔːt ˈsɜːkɪt ɪˌvæljuːˈeɪʃn/ evaluasi pintas
    De Morgan's laws/də ˈmɔːɡənz lɔːz/ hukum De Morgan
    while loop/waɪl luːp/ perulangan while
    infinite loop/ˈɪnfɪnət luːp/ perulangan tak hingga
    2.2

    Boolean Expressions · ⁨Ekspresi Boolean⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.2.A: Mengembangkan kode untuk membuat ekspresi Boolean dengan operator relasional dan menentukan hasil dari ekspresi-ekspresi tersebut.

    • 2.2.A.1 Nilai-nilai dapat dibandingkan menggunakan operator relasional == dan != untuk menentukan apakah nilai-nilai tersebut sama. Dengan tipe primitif, ini membandingkan nilai primitif itu sendiri. Dengan tipe referensi, ini membandingkan referensi objeknya.
    • 2.2.A.2 Nilai numerik dapat dibandingkan menggunakan operator relasional <, >, <=, dan >= untuk menentukan hubungan antara nilai-nilai tersebut.
    • 2.2.A.3 Sebuah ekspresi yang melibatkan operator relasional akan mengevaluasi menjadi nilai Boolean.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Gerbang logika & half-adder

    Ekspresi boolean dievaluasi menjadi true atau false, menggunakan operator relasional: == (sama dengan), != (tidak sama dengan), <, >, <=, >=. Perhatikan bahwa == membandingkan nilai primitif tetapi referensi objek untuk objek, jadi gunakan .equals untuk Strings.

    Tiga keluarga operator: aritmatika, relasional, dan logika
    Tiga keluarga operator: aritmatika, relasional, dan logika
    Explore · ⁨Jelajahi⁩

    Explore the AND truth table · ⁨Jelajahi tabel kebenaran 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. · ⁨Ekspresi Boolean mengevaluasi menjadi true atau false. AND benar hanya jika kedua operand benar; aktifkan input untuk melihat keempat kasus.⁩

    2.3

    The if Statement · ⁨Pernyataan if⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.3.A: Mengembangkan kode untuk merepresentasikan proses logis percabangan menggunakan pernyataan seleksi dan menentukan hasil dari proses-proses tersebut.

    • 2.3.A.1 Pernyataan seleksi mengubah eksekusi berurutan dari pernyataan-pernyataan.
    • 2.3.A.2 Sebuah pernyataan if adalah jenis pernyataan seleksi yang mempengaruhi alur kontrol dengan mengeksekusi segmen kode yang berbeda berdasarkan nilai sebuah ekspresi Boolean.
    • 2.3.A.3 Seleksi satu arah (pernyataan if) digunakan ketika ada segmen kode yang harus dieksekusi di bawah kondisi tertentu. Dalam hal ini, tubuh hanya dieksekusi ketika ekspresi Boolean bernilai true.
    • 2.3.A.4 Seleksi dua arah (pernyataan if-else) digunakan ketika ada dua segmen kode—satu untuk dieksekusi ketika ekspresi Boolean bernilai true dan segmen lain untuk ketika ekspresi Boolean bernilai false. Dalam kasus ini, tubuh dari if dieksekusi ketika ekspresi Boolean bernilai true, dan tubuh dari else dieksekusi ketika ekspresi Boolean bernilai false.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

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

    Bahasa Indonesia

    Pernyataan if menjalankan blok hanya ketika kondisinya true; sebuah else opsional memberikan alternatif:

    if (score >= 60) {
        System.out.println("Pass");
    } else {
        System.out.println("Fail");
    }
    
    Lampu lalu lintas: seleksi memilih cabang mana yang berjalan, sama seperti pernyataan if memilih jalur kode
    Lampu lalu lintas: seleksi memilih cabang mana yang berjalan, sama seperti pernyataan if memilih jalur kode
    Explore · ⁨Jelajahi⁩

    See which branch an if chooses · ⁨Lihat cabang mana yang dipilih 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. · ⁨Perintah if menjalankan isinya hanya ketika kondisi benar, jika tidak ia melewatkan ke else. Geser skor melintasi batas dan lihat nilai huruf berubah.⁩

    2.4

    Nested if Statements · ⁨Pernyataan if Bersarang⁩

    Syllabus · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 2.4.A: Mengembangkan kode untuk merepresentasikan proses logis percabangan bersarang dan menentukan hasil dari proses-proses tersebut.

    • 2.4.A.1 Pernyataan if yang bersarang terdiri dari pernyataan-pernyataan if, if-else, atau if-else-if di dalam pernyataan-pernyataan if, if-else, atau if-else-if.
    • 2.4.A.2 Ekspresi Boolean dari pernyataan if dalam yang bersarang hanya akan dievaluasi jika ekspresi Boolean dari pernyataan if luar mengevaluasi menjadi true.
    • 2.4.A.3 Seleksi banyak arah (pernyataan if-else-if) digunakan ketika ada serangkaian ekspresi dengan segmen kode yang berbeda untuk setiap kondisinya. Seleksi banyak arah dilakukan sedemikian rupa sehingga tidak lebih dari satu segmen kode yang dieksekusi berdasarkan ekspresi pertama yang mengevaluasi menjadi true. Jika tidak ada ekspresi yang mengevaluasi menjadi true dan terdapat pernyataan else terakhir, maka tubuh dari else akan dieksekusi.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

    Placing an if inside another, or chaining with else if, tests several cases in order. Only the first matching branch runs:

    Bahasa Indonesia

    Menempatkan sebuah if di dalam lainnya, atau merangkai dengan else if, menguji beberapa kasus secara berurutan. Hanya cabang pertama yang cocok yang akan berjalan:

    if (g >= 90) grade = 'A';
    else if (g >= 80) grade = 'B';
    else grade = 'C';
    
    2.5

    Compound Boolean Expressions · ⁨Ekspresi Boolean Majemuk⁩

    Syllabus · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 2.5.A: Mengembangkan kode untuk merepresentasikan ekspresi Boolean majemuk dan menentukan hasil dari ekspresi-ekspresi tersebut.

    • 2.5.A.1 Operator logika ! (not), && (and), dan || (or) digunakan bersama ekspresi Boolean. Ekspresi !a mengevaluasi menjadi true jika a bernilai false dan mengevaluasi menjadi false sebaliknya. Ekspresi a && b mengevaluasi menjadi true jika baik a maupun b bernilai true dan mengevaluasi menjadi false sebaliknya. Ekspresi a || b mengevaluasi menjadi true jika a bernilai true, b bernilai true, atau keduanya, dan mengevaluasi menjadi false sebaliknya. Urutan prioritas untuk mengevaluasi operator logika adalah ! (not), && (and), kemudian || (or). Ekspresi yang melibatkan operator logika akan mengevaluasi menjadi nilai Boolean.
    • 2.5.A.2 Evaluasi short-circuit terjadi ketika hasil dari operasi logika menggunakan && atau || dapat ditentukan hanya dengan mengevaluasi ekspresi Boolean pertama. Dalam kasus ini, ekspresi Boolean kedua tidak akan dievaluasi.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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).

    Bahasa Indonesia
    Evaluasi short-circuit

    Operator logika menggabungkan kondisi: && (and – keduanya true), || (or – setidaknya satu true), ! (not – kebalikan). Java menggunakan evaluasi short-circuit: && berhenti jika sisi kiri false, dan || berhenti jika sisi kiri true – berguna untuk mencegah kesalahan, mis. if (n != 0 && total / n > 5).

    2.6

    Comparing Boolean Expressions · ⁨Membandingkan Ekspresi Boolean⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.6.A: Membandingkan ekspresi Boolean yang ekuivalen.

    • 2.6.A.1 Dua ekspresi Boolean disebut ekuivalen jika mereka mengevaluasi menjadi nilai yang sama dalam semua kasus. Tabel kebenaran dapat digunakan untuk membuktikan bahwa ekspresi Boolean adalah ekuivalen.
    • 2.6.A.2 Hukum De Morgan dapat diterapkan pada ekspresi Boolean untuk menciptakan ekspresi Boolean yang ekuivalen. Di bawah Hukum De Morgan, ekspresi Boolean !(a && b) ekuivalen dengan !a || !b dan ekspresi Boolean !(a || b) ekuivalen dengan !a && !b.

    Tujuan Pembelajaran 2.6.B: Mengembangkan kode untuk membandingkan referensi objek menggunakan ekspresi Boolean dan menentukan hasil dari ekspresi-ekspresi tersebut.

    • 2.6.B.1 Dua variabel yang berbeda dapat menyimpan referensi ke objek yang sama. Referensi objek dapat dibandingkan menggunakan == dan !=.
    • 2.6.B.2 Sebuah referensi objek dapat dibandingkan dengan null, menggunakan == atau !=, untuk menentukan apakah referensi tersebut benar-benar merujuk pada sebuah objek.
    • 2.6.B.3 Kelas-kelas sering mendefinisikan metode equals mereka sendiri, yang dapat digunakan untuk menentukan kriteria kesetaraan untuk dua objek dari kelas tersebut. Kesetaraan dua objek paling sering ditentukan menggunakan atribut-atribut dari kedua objek tersebut.
      • Pernyataan pengecualian: Mengimpa metode equals berada di luar ruang lingkup kursus dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Hukum De Morgan menulis ulang negasi: !(a && b) sama dengan !a || !b, dan !(a || b) sama dengan !a && !b. Dua ekspresi boolean ekuivalen jika mereka menghasilkan hasil yang sama untuk setiap input – tabel kebenaran membuktikannya. Menyederhanakan kondisi dengan cara ini adalah tugas ujian yang umum.

    2.7

    while Loops · ⁨Perulangan while⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.7.A: Identifikasi kapan proses iteratif diperlukan untuk mencapai hasil yang diinginkan.

    • 2.7.A.1 Iterasi adalah bentuk pengulangan. Pernyataan iterasi mengubah alur kontrol dengan mengulang segmen kode nol atau lebih kali selama ekspresi Boolean yang mengontrol perulangan mengevaluasi ke true.
    • 2.7.A.2 Perulangan tak hingga terjadi ketika ekspresi Boolean dalam pernyataan iteratif selalu mengevaluasi ke true.
    • 2.7.A.3 Badan perulangan dari pernyataan iteratif tidak akan dieksekusi jika ekspresi Boolean awalnya mengevaluasi ke false.
    • 2.7.A.4 Kesalahan off by one terjadi ketika pernyataan iterasi melakukan perulangan satu kali terlalu banyak atau satu kali terlalu sedikit.

    Tujuan Pembelajaran 2.7.B: Kembangkan kode untuk merepresentasikan proses iteratif menggunakan while loops dan tentukan hasil dari proses-proses tersebut.

    • 2.7.B.1 Loop while adalah jenis pernyataan iteratif. Dalam loop while, ekspresi Boolean dievaluasi sebelum setiap iterasi badan perulangan, termasuk pertama. Ketika ekspresi mengevaluasi ke true, badan perulangan dieksekusi. Ini berlanjut hingga ekspresi Boolean mengevaluasi ke false, di mana iterasi berhenti.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 无限循环:

    Bahasa Indonesia

    Perulangan while mengulang selama kondisinya tetap true, menguji sebelum setiap putaran. Anda harus mengubah sesuatu di dalamnya agar perulangan akhirnya berhenti, atau itu akan menjadi perulangan tak hingga:

    Tiga jenis perulangan berbeda dalam hal di mana kondisi diuji
    Tiga jenis perulangan berbeda dalam hal di mana kondisi diuji
    int i = 0;
    while (i < 5) {
        System.out.println(i);
        i++;
    }
    
    Explore · ⁨Jelajahi⁩

    Trace a while loop · ⁨Telusuri perulangan 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. · ⁨Perulangan while berulang selama kondisinya tetap benar, memperbarui variabelnya setiap kali melewati. Telusuri untuk melihat penjumlahan kuadrat terbentuk.⁩

    2.8

    for Loops · ⁨Perulangan for⁩

    Syllabus · ⁨Silabus⁩
    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).
    Bahasa Indonesia

    Tujuan Pembelajaran 2.8.A: Mengembangkan kode untuk merepresentasikan proses iteratif menggunakan loop for dan menentukan hasil dari proses-proses ini.

    • 2.8.A.1 Loop for adalah jenis pernyataan iteratif. Ada tiga bagian dalam header loop for: inisialisasi, ekspresi Boolean, dan pembaruan.
    • 2.8.A.2 Dalam loop for, pernyataan inisialisasi hanya dieksekusi sekali sebelum evaluasi ekspresi Boolean pertama. Variabel yang diinisialisasi disebut sebagai variabel kontrol loop. Ekspresi Boolean dievaluasi segera setelah variabel kontrol loop diinisialisasi dan kemudian mengikuti setiap eksekusi pernyataan inkrement hingga menjadi false. Pada setiap iterasi, pembaruan dieksekusi setelah seluruh badan perulangan dieksekusi dan sebelum ekspresi Boolean dievaluasi lagi.
    • 2.8.A.3 Loop for dapat ditulis ulang menjadi loop while yang ekuivalen (dan sebaliknya).

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

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

    A for and an equivalent while do the same work; be able to convert between them.

    Bahasa Indonesia

    Perulangan for menggabungkan inisialisasi, kondisi, dan pembaruan dalam satu baris – terbaik ketika Anda mengetahui jumlah pengulangannya:

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

    Sebuah for dan sebuah while ekuivalen melakukan pekerjaan yang sama; mampu mengonversi di antara keduanya.

    Garis perakitan: perulangan mengulang proses untuk setiap item, seperti for dan while
    Garis perakitan: perulangan mengulang proses untuk setiap item, seperti for dan while
    Explore · ⁨Jelajahi⁩

    Trace a for loop · ⁨Telusuri perulangan 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. · ⁨Perulangan for berjalan sejumlah kali tetap, pengentornya melintasi suatu rentang. Perhatikan pengantar dan total berjalan maju satu kali melewati pada satu waktu.⁩

    2.9

    Building Complete Selection and Iteration Algorithms · ⁨Membangun Algoritma Seleksi dan Iterasi Lengkap⁩

    Syllabus · ⁨Silabus⁩
    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
    Bahasa Indonesia

    Tujuan Pembelajaran 2.9.A: Kembangkan kode untuk algoritma standar dan asli (tanpa struktur data) dan tentukan hasil dari algoritma-algoritma tersebut.

    • 2.9.A.1 Terdapat algoritma standar untuk:
      • mengidentifikasi apakah sebuah bilangan bulat habis dibagi oleh bilangan bulat lain atau tidak
      • mengidentifikasi digit-digit individu dalam sebuah bilangan bulat
      • menentukan frekuensi terpenuhinya kriteria tertentu
      • menentukan nilai minimum atau maksimum
      • menghitung jumlah atau rata-rata

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Gabungkan perulangan dan kondisi untuk memecahkan masalah nyata – hitung, jumlahkan, temukan maksimum, atau uji sifat tertentu:

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

    Dua pola bilangan bulat yang ujian uji langsung menggunakan % dan /. Untuk membaca digit bilangan bulat satu per satu, berulang kali ambil n % 10 (digit terakhir) lalu n = n / 10 (buang digit tersebut). Untuk menguji keterbagian, n % d == 0 berarti n habis dibagi oleh d. Gabungkan dengan counter untuk menemukan frekuensi kriteria tertentu terpenuhi.

    Pola standar seperti total berjalan, counter, atau flag (boolean yang mencatat apakah sesuatu terjadi) muncul berulang kali sepanjang kursus.

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    flag/flæɡ/ flag
    nested loop/ˈnestɪd luːp/ loop bersarang
    Run-time analysis/rʌn taɪm əˈnæləsɪs/ Analisis waktu berjalan
    2.10

    String Algorithms · ⁨Algoritma String⁩

    Syllabus · ⁨Silabus⁩
    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
    Bahasa Indonesia

    Tujuan Pembelajaran 2.10.A: Mengembangkan kode untuk algoritma standar dan asli yang melibatkan string dan menentukan hasil dari algoritma-algoritma ini.

    • 2.10.A.1 Terdapat algoritma string standar untuk:
      • mencari apakah satu atau lebih substring memiliki properti tertentu
      • menentukan jumlah substring yang memenuhi kriteria tertentu
      • membuat string baru dengan karakter yang dibalik

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    English

    Loop through a string by index to process each character:

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

    Bahasa Indonesia

    Perulangan melalui string berdasarkan indeks untuk memproses setiap karakter:

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

    Tugas典型: hitung kemunculan, bangun salinan terbalik atau difilter, atau uji apakah satu string mengandung string lain.

    2.11

    Nested Iteration · ⁨Iterasi Bersarang⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.11.A: Mengembangkan kode untuk merepresentasikan proses iteratif bersarang dan menentukan hasil dari proses-proses tersebut.

    • 2.11.A.1 Pernyataan iterasi bersarang adalah pernyataan iterasi yang muncul di dalam tubuh pernyataan iterasi lainnya. Ketika sebuah perulangan disarungkan di dalam perulangan lain, perulangan dalam harus menyelesaikan seluruh iterasinya sebelum perulangan luar dapat melanjutkan ke iterasi berikutnya.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Perulangan bersarang menempatkan satu perulangan di dalam yang lain; perulangan dalam selesai sepenuhnya untuk setiap putaran luar. Jika perulangan luar berjalan $n$ kali dan dalam $m$ kali, badannya berjalan $n\times m$ kali – dasar untuk memproses grid dan membandingkan semua pasangan.

    2.12

    Informal Run-Time Analysis · ⁨Analisis Run-Time Informal⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 2.12.A: Menghitung jumlah eksekusi pernyataan dan melakukan perbandingan waktu eksekusi informal terhadap pernyataan-pernyataan iteratif.

    • 2.12.A.1 Jumlah eksekusi pernyataan menunjukkan berapa kali sebuah pernyataan dieksekusi oleh program. Jumlah eksekusi pernyataan sering dihitung secara informal melalui pelacakan dan analisis terhadap pernyataan-pernyataan iteratif.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Tingkat pertumbuhan Big-O

    Analisis run-time menghitung berapa banyak langkah dasar yang diambil algoritma saat ukuran input $n$ bertambah. Hitung eksekusi pernyataan terdalam: satu loop atas $n$ item bersifat linear ($n$ langkah); dua loop bersarang atas $n$ bersifat kuadratik ($n^2$). Penghitungan informal ini memungkinkan Anda membandingkan efisiensi dua algoritma.

    Bagaimana waktu berjalan tumbuh seiring jumlah elemen n
    Bagaimana waktu berjalan tumbuh seiring jumlah elemen n

    Keterampilan ujian: untuk perulangan bersarang, mampu menyatakan berapa kali pernyataan dalam berjalan berdasarkan batas perulangan – pertanyaan pilihan ganda yang sering muncul.

    Contoh dikerjakan. Berapa banyak bintang yang dicetak ini?

    for (int i = 0; i < 4; i++)
        for (int j = 0; j < i; j++)
            System.out.print("*");
    

    Loop dalam menjalankan i kali untuk setiap loop luar i: 0 + 1 + 2 + 3 = 6 bintang. Ketika batas dalam adalah variabel luar, totalnya adalah jumlah segitiga $0+1+\dots+(n-1)=\dfrac{n(n-1)}{2}$ – di sini $\dfrac{4\times3}{2}=6$ – bukan total penuh $n^2=16$ dari loop bersarang persegi panjang.

    Explore · ⁨Jelajahi⁩

    Compare how algorithms scale · ⁨Bandingkan bagaimana algoritma berskala⁩

    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)$. · ⁨Waktu eksekusi menggambarkan bagaimana jumlah langkah tumbuh seiring ukuran input $n$. Tingkatkan $n$ dan lihat linear $O(n)$ menjauh jauh dari kuadratik $O(n^2)$.⁩

    2.12

    Exam tips · ⁨Tips ujian⁩

    English
    • 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.
    Bahasa Indonesia
    • Tentukan kondisi batas dengan benar: gunakan < vs <= secara sengaja, dan perhatikan iterasi pertama dan terakhir dari setiap loop (off-by-one adalah bug klasik).
    • Bangun kondisi majemuk dengan &&, ||, ! dan ingat evaluasi short-circuit (tempatkan pengecekan null terlebih dahulu).
    • Jejak loop bersarang dengan menghitung berapa kali badan dalam berjalan secara total.
    • Pilih struktur yang tepat — if/else if untuk rentang, loop untuk pengulangan — dan hindari loop tak hingga dengan memperbarui variabel loop.
    • Terapkan hukum De Morgan saat Anda menyederhanakan atau menegatifkan kondisi boolean.
  • 3

    Class Creation · ⁨Pembuatan Kelas⁩

    Watch lesson · ⁨Tonton pelajaran⁩
    3.1

    Abstraction and Program Design · ⁨Abstraksi dan Desain Program⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.1.A: Representasikan desain program menggunakan bahasa alami atau membuat diagram yang menunjukkan kelas-kelas dalam program dan abstraksi data serta prosedural yang ditemukan di setiap kelas dengan menyertakan semua atribut dan perilaku.

    • 3.1.A.1 Abstraksi adalah proses mengurangi kompleksitas dengan memfokuskan pada ide utama. Dengan menyembunyikan detail yang tidak relevan dengan pertanyaan saat ini dan mengumpulkan detail yang terkait dan berguna, abstraksi mengurangi kompleksitas dan memungkinkan seseorang untuk memfokuskan pada ide tersebut.
    • 3.1.A.2 Abstraksi data menyediakan pemisahan antara sifat abstrak dari tipe data dan detail konkret dari representasinya. Abstraksi data mengelola kompleksitas dengan memberikan nama pada data tanpa merujuk pada detail spesifik representasinya. Data dapat berbentuk variabel tunggal atau kumpulan data, seperti dalam kelas atau set data.
    • 3.1.A.3 Atribut adalah jenis abstraksi data yang didefinisikan dalam kelas di luar metode atau konstruktor apa pun. Variabel instance adalah atribut yang nilainya unik untuk setiap instance dari kelas tersebut. Variabel kelas adalah atribut yang dibagikan oleh semua instance dari kelas tersebut.
    • 3.1.A.4 Abstraksi prosedural menyediakan nama untuk suatu proses dan memungkinkan sebuah metode digunakan hanya dengan mengetahui apa yang dilakukannya, bukan bagaimana hal itu dilakukan. Melalui dekomposisi metode, seorang programmer memecah perilaku kelas yang lebih besar menjadi perilaku yang lebih kecil dengan membuat metode untuk mewakili setiap perilaku kecil individu. Abstraksi prosedural dapat mengekstrak fitur bersama untuk mengeneralisasi fungsi daripada menduplikasi kode. Hal ini memungkinkan penggunaan kembali kode, yang membantu mengelola kompleksitas.
    • 3.1.A.5 Menggunakan parameter memungkinkan prosedur digeneralisasikan, memungkinkan prosedur digunakan kembali dengan rentang nilai input atau argumen.
    • 3.1.A.6 Menggunakan abstraksi prosedural dalam program memungkinkan programmer mengubah internal metode (untuk membuatnya lebih cepat, lebih efisien, menggunakan penyimpanan kurang, dll.) tanpa perlu memberi tahu pengguna metode tentang perubahan tersebut selama tanda tangan metode dan apa yang dilakukan metode tetap terjaga.
    • 3.1.A.7 Sebelum mengimplementasikan kelas, sangat membantu meluangkan waktu untuk merancang setiap kelas termasuk atribut dan perilakunya. Desain ini dapat direpresentasikan menggunakan bahasa alami atau diagram.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    Teka-teki yang sedang berlangsung: kelas dan metode adalah bagian modular dari desain program yang lebih besar
    Teka-teki yang sedang berlangsung: kelas dan metode adalah bagian modular dari desain program yang lebih besar

    Abstraksi berarti menyembunyikan detail di balik antarmuka sederhana – Anda menggunakan String tanpa tahu bagaimana cara menyimpan karakter. Desain yang baik memecah masalah menjadi kelas-kelas, masing-masing bertanggung jawab atas satu ide. Topik ini tentang menulis kelas Anda sendiri.

    Mendekomposisi program menjadi modul dan sub-modul
    Mendekomposisikan program menjadi modul dan sub-modul
    3.2

    The Impact of Program Design · ⁨Dampak Desain Program⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.2.A: Jelaskan implikasi sosial dan etika dari sistem komputasi.

    • 3.2.A.1 Keandalan sistem merujuk pada kemampuan program untuk menjalankan tugasnya sesuai harapan di bawah kondisi yang ditetapkan tanpa kegagalan. Pemrogram harus berusaha memaksimalkan keandalan sistem dengan menguji program dengan berbagai kondisi.
    • 3.2.A.2 Pembuatan program memiliki dampak pada masyarakat, ekonomi, dan budaya. Dampak-dampak ini dapat bersifat menguntungkan maupun merugikan. Program yang dirancang untuk memenuhi kebutuhan atau memecahkan masalah dapat menimbulkan efek merugikan tak terduga di luar penggunaannya yang dimaksudkan.
    • 3.2.A.3 Isu hukum dan kekhawatiran terkait hak kekayaan intelektual muncul saat pembuatan program. Para pemrogram sering kali menggunakan ulang kode yang ditulis oleh orang lain dan dipublikasikan sebagai sumber terbuka (open source) serta gratis digunakan. Penggunaan kode yang tidak dipublikasikan sebagai sumber terbuka mengharuskan pemrogram untuk mendapatkan izin dan seringkali membeli kode tersebut sebelum mengintegrasikannya ke dalam program mereka.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Pilihan desain mempengaruhi apakah kode benar, mudah dibaca, dan dapat digunakan kembali. Enkapsulasi – menyimpan data secara privat dan mengeksposnya hanya melalui metode – melindungi state objek dari penyalahgunaan dan memungkinkan Anda mengubah bagian dalam tanpa merusak pengguna kelas. Penamaan yang bijaksana, metode tunggal-tujuan, dan pengujian mengurangi bug.

    Desain juga membawa tanggung jawab di luar kode. Keandalan sistem - sebuah program yang menjalankan tugasnya sesuai harapan, tanpa kegagalan - adalah sesuatu yang pemrogram harus maksimalkan melalui desain dan pengujian yang hati-hati. Program memiliki dampak nyata pada masyarakat, ekonomi, dan budaya yang dapat baik menguntungkan maupun merugikan. Dan membuat program menimbulkan kekhawatiran hukum dan hak kekayaan intelektual: pemrogram sering menggunakan ulang kode yang dipublikasikan sebagai open source dan gratis digunakan, tetapi harus menghormati lisensinya dan memberikan kredit daripada meniru karya orang lain sebagai milik mereka sendiri.

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Abstraction/əbˈstrækʃn/ Abstraksi
    Encapsulation/ɪnˌkæpsjʊˈleɪʃn/ Pencapsulan (Encapsulation)
    System reliability/ˈsɪstəm rɪˌlaɪəˈbɪlɪti/ Keandalan sistem
    legal and intellectual-property/ˈliːɡl ænd ˌɪntəˈlektʃuːəl ˈprɒpəti/ hukum dan properti intelektual
    open source/ˈəʊpən sɔːs/ open source
    instance variables/ˈɪnstəns ˈveərɪəblz/ variabel instance
    3.3

    The Anatomy of a Class · ⁨Anatomi Kelas⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.3.A: Mengembangkan kode untuk menetapkan batasan akses dan visibilitas pada kelas, data, konstruktor, dan metode.

    • 3.3.A.1 Encapsulasi data adalah teknik di mana detail implementasi sebuah kelas disembunyikan dari kelas eksternal. Kata kunci public dan private memengaruhi akses terhadap kelas, data, konstruktor, dan metode. Kata kunci private membatasi akses hanya pada kelas pengumuman, sedangkan kata kunci public memungkinkan akses dari kelas di luar kelas pengumuman.
    • 3.3.A.2 Dalam kursus ini, kelas selalu ditetapkan sebagai public dan dideklarasikan dengan kata kunci class.
    • 3.3.A.3 Dalam kursus ini, konstruktor selalu ditetapkan sebagai public.
    • 3.3.A.4 Variabel instance milik objek, dan setiap objek memiliki salinan variabelnya sendiri.
    • 3.3.A.5 Akses terhadap atribut harus dijaga tetap internal dalam kelas guna mencapai encapsulasi. Oleh karena itu, praktik pemrograman yang baik adalah menetapkan variabel instance untuk atribut-atribut tersebut sebagai private kecuali spesifikasi kelas menyatakan sebaliknya.
    • 3.3.A.6 Akses terhadap perilaku bisa bersifat internal atau eksternal terhadap kelas. Metode yang ditetapkan sebagai public dapat diakses secara internal maupun eksternal terhadap sebuah kelas, sementara metode yang ditetapkan sebagai private hanya dapat diakses secara internal terhadap kelas.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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:

    Bahasa Indonesia

    Sebuah kelas memiliki tiga bagian: variabel instance (field – data objek), konstruktor (membangun objek), dan metode (perilaku). Field biasanya private; metode biasanya public:

    Diagram kelas: atribut privat dan publik metode
    Diagram kelas: atribut privat dan publik metode
    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
    }
    
    Cetak biru: sebuah kelas adalah template yang mendefinisikan bagaimana objek tipe tersebut dibangun
    Cetak biru: sebuah kelas adalah template yang mendefinisikan bagaimana objek tipe tersebut dibangun
    Explore · ⁨Jelajahi⁩

    See an object's fields as boxes · ⁨Lihat bidang objek sebagai kotak-kotak⁩

    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. · ⁨Kelas mengelompokkan data terkait (bidangnya) dan metode. Setiap objek mendapatkan set kotak bidangnya sendiri; menugaskan ke salah satunya hanya mengubah objek tersebut.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    constructor/kənˈstrʌktə/ konstruktor
    accessor (getter)/əkˈsesə/ aksesor (getter)
    3.4

    Constructors · ⁨Konstruktor⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.4.A: Mengembangkan kode untuk mendeklarasikan variabel instance bagi atribut yang akan diinisialisasi dalam tubuh konstruktor sebuah kelas.

    • 3.4.A.1 Status (state) suatu objek merujuk pada atribut dan nilainya pada waktu tertentu, dan didefinisikan oleh variabel instance yang dimiliki objek tersebut. Hal ini mendefinisikan hubungan memiliki (has-a) antara objek dan variabel instance-nya.
    • 3.4.A.2 Konstruktor digunakan untuk menetapkan status awal sebuah objek, yang harus mencakup nilai awal untuk semua variabel instance. Ketika konstruktor dipanggil, memori dialokasikan untuk objek dan referensi objek yang terkait dikembalikan. Parameter konstruktor, jika ditentukan, menyediakan data untuk menginisialisasi variabel instance.
    • 3.4.A.3 Ketika objek yang dapat diubah (mutable object) merupakan parameter konstruktor, variabel instance harus diinisialisasi dengan salinan objek yang dirujuk. Dengan cara ini, variabel instance tidak memegang referensi ke objek asli, dan metode dicegah dari memodifikasi status objek asli.
    • 3.4.A.4 Ketika tidak ada konstruktor yang ditulis, Java menyediakan konstruktor tanpa parameter, dan variabel instance diatur ke nilai default sesuai dengan tipe data atributnya. Konstruktor ini disebut konstruktor default.
    • 3.4.A.5 Nilai default untuk atribut bertipe int adalah 0. Nilai default untuk atribut bertipe double adalah 0.0. Nilai default untuk atribut bertipe boolean adalah false. Nilai default untuk tipe referensi adalah null.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Sebuah konstruktor memiliki nama yang sama dengan kelas dan tidak memiliki tipe kembalian. Ia berjalan ketika Anda menulis new, dan tugasnya adalah menginisialisasi field. Sebuah kelas dapat memiliki beberapa konstruktor dengan daftar parameter yang berbeda (overloading); sebuah konstruktor tanpa-argumen menetapkan nilai default.

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    overloading/ˌəʊvəˈləʊdɪŋ/ pemuatan ulang
    3.5

    Methods: How to Write Them · ⁨Metode: Cara Menulisnya⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.5.A: Mengembangkan kode untuk mendefinisikan perilaku objek melalui metode yang ditulis dalam kelas menggunakan nilai primitif dan menentukan hasil pemanggilan metode-metode tersebut.

    • 3.5.A.1 Metode void tidak mengembalikan nilai. Header-nya berisi kata kunci void sebelum nama metode.
    • 3.5.A.2 Metode non-void mengembalikan satu nilai. Header-nya mencakup tipe kembali (return type) menggantikan kata kunci void.
    • 3.5.A.3 Dalam metode non-void, ekspresi return yang kompatibel dengan tipe kembali dievaluasi, dan nilainya dikembalikan. Ini disebut kembali melalui nilai (return by value).
    • 3.5.A.4 Kata kunci return digunakan untuk mengembalikan alur kendali ke titik di mana metode atau konstruktor dipanggil. Kode apa pun yang berada secara berurutan setelah pernyataan return tidak akan pernah dieksekusi. Mengeksekusi pernyataan return di dalam pernyataan pemilihan atau iterasi akan menghentikan pernyataan tersebut dan keluar dari metode atau konstruktor.
    • 3.5.A.5 Metode aksesor memungkinkan objek dari kelas lain untuk mendapatkan salinan nilai variabel instance atau variabel kelas. Metode aksesor adalah metode non-void.
    • 3.5.A.6 Metode mutator (modifikator) adalah metode yang mengubah nilai variabel instance atau variabel kelas. Metode mutator sering kali merupakan metode void.
    • 3.5.A.7 Metode dengan parameter menerima nilai melalui parameter tersebut dan menggunakan nilai-nilai tersebut dalam menyelesaikan tugas metode.
    • 3.5.A.8 Ketika argumen adalah nilai primitif, parameter diinisialisasi dengan salinan nilai tersebut. Perubahan pada parameter tidak berpengaruh pada argumen yang bersangkutan.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Sebuah metode memiliki signature, tipe kembalian, dan badan. Sebuah aksesor (getter) mengembalikan informasi tanpa mengubah objek; sebuah mutator (setter) mengubah field. Metode yang mengembalikan nilai harus memiliki return dari tipe yang benar di setiap jalur; metode void tidak mengembalikan apa pun.

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

    Follow a method call and its return · ⁨Ikuti pemanggilan metode dan pengembaliannya⁩

    Calling a method pushes a frame with its parameters; when it hits return, the frame pops and the value goes back to the caller. · ⁨Memanggil metode mendorong bingkai dengan parameternya; ketika mencapai return, bingkai dilepas dan nilai kembali ke Caller.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    mutator (setter)/mjuːˈteɪtə/ mutator (setter)
    static (class) variable/ˈstætɪk ˈveərɪəbl/ variabel statis (kelas)
    3.6

    Passing and Returning References of an Object · ⁨Mengirim dan Mengembalikan Referensi Objek⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.6.A: Mengembangkan kode untuk mendefinisikan perilaku objek melalui metode yang ditulis dalam kelas menggunakan referensi objek dan menentukan hasil pemanggilan metode-metode tersebut.

    • 3.6.A.1 Ketika argumen adalah referensi objek, parameter diinisialisasi dengan salinan dari referensi tersebut; hal ini tidak membuat salinan objek baru yang independen. Jika parameter merujuk pada objek yang dapat diubah (mutable), metode atau konstruktor dapat menggunakan referensi ini untuk mengubah keadaan objek. Merupakan praktik pemrograman yang baik untuk tidak memodifikasi objek yang dapat diubah yang dilempar sebagai parameter kecuali diperlukan dalam spesifikasi.
    • 3.6.A.2 Ketika ekspresi return mengevaluasi ke sebuah referensi objek, maka referensilah yang dikembalikan, bukan referensi ke salinan objek baru.
    • 3.6.A.3 Metode tidak dapat mengakses data pribadi dan metode dari parameter yang memegang referensi ke objek kecuali jika parameter tersebut memiliki tipe yang sama dengan kelas pembungkus dari metode tersebut.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia
    = menyalin referensi, bukan objek

    Ketika Anda mengirim objek ke metode, Java menyalin referensi, sehingga metode bertindak pada objek yang sama – perubahan pada field-nya terlihat oleh pemanggil. (Primitif disalin oleh nilai, jadi perubahannya tidak.) Metode juga dapat mengembalikan referensi ke sebuah objek. Karena String bersifat immutable, mengirimkannya aman; mengirim objek yang dapat diubah memungkinkan metode mengubahnya.

    Java mengirim by value: metode mendapatkan salinan; true pass by reference, yang tidak dimiliki Java, akan memungkinkannya assigns ulang variabel pemanggil
    Java selalu mengirim by value (kiri): metode mendapatkan salinan dari referensinya. True pass by reference (kanan) – yang tidak dimiliki Java – akan memungkinkannya metode assigns ulang variabel pemanggil itu sendiri.

    Keterampilan ujian: ketahui bahwa memutasi field objek di dalam metode mempengaruhi yang asli, tetapi assigns ulang parameter (param = new...) tidak mempengaruhi pemanggil.

    Contoh terpecahkan. Misalkan s adalah Student dengan skor 50, dan kami memanggil 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
    }
    

    Baris (1) mengubah objek yang ditunjuk oleh s, sehingga pemanggil sekarang melihat 100. Baris (2) membuat salihan sendiri dari metode yang menunjuk ke objek baru – s pemanggil tetap utuh – dan baris (3) hanya mempengaruhi objek baru itu. Setelah panggilan, s.getScore() adalah 100: mutasinya menempel, assigns ulangnya tidak.

    3.7

    Class Variables and Class Methods · ⁨Variabel Kelas dan Metode Kelas⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.7.A: Mengembangkan kode untuk mendefinisikan perilaku kelas melalui metode kelas.

    • 3.7.A.1 Metode kelas tidak dapat mengakses atau mengubah nilai variabel instance atau memanggil metode instance tanpa dilemparkan sebuah instance dari kelas tersebut melalui parameter.
    • 3.7.A.2 Metode kelas dapat mengakses atau mengubah nilai variabel kelas dan dapat memanggil metode kelas lainnya.

    Tujuan Pembelajaran 3.7.B: Mengembangkan kode untuk mendeklarasikan variabel kelas yang milik kelas.

    • 3.7.B.1 Variabel kelas milik kelas, dengan semua objek dari sebuah kelas berbagi satu salinan dari variabel kelas tersebut. Variabel kelas ditandai dengan kata kunci static sebelum tipe variabel.
    • 3.7.B.2 Variabel kelas yang ditunjuk public diakses di luar kelas dengan menggunakan nama kelas dan operator titik, karena mereka terkait dengan kelas, bukan objek dari kelas.
    • 3.7.B.3 Ketika sebuah variabel dideklarasikan final, nilainya tidak dapat dimodifikasi.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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().

    Bahasa Indonesia
    field statis vs instance

    Sebuah variabel statis (kelas), ditandai static, dibagi oleh semua objek dari kelas – satu salinan total (misalnya counter berapa banyak objek yang ada). Metode statis milik kelas dan tidak dapat menggunakan field instance secara langsung. Akseslah mereka dengan nama kelas: Student.getCount().

    3.8

    Scope and Access · ⁨Ruang Lingkup dan Akses⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.8.A: Menjelaskan di mana variabel dapat digunakan dalam kode.

    • 3.8.A.1 Variabel lokal adalah variabel yang dideklarasikan di header atau badan blok kode. Variabel lokal hanya dapat diakses di blok tempat mereka dideklarasikan. Karena konstruktor dan metode adalah blok kode, parameter untuk konstruktor atau metode juga dianggap sebagai variabel lokal. Variabel-variabel ini hanya dapat digunakan di dalam konstruktor atau metode dan tidak dapat dideklarasikan sebagai public atau private.
    • 3.8.A.2 Ketika ada variabel lokal atau parameter dengan nama yang sama dengan variabel instance, nama variabel akan merujuk ke variabel lokal alih-alih variabel instance di dalam badan konstruktor atau metode.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    Ruang lingkup adalah tempat nama terlihat. Variabel lokal yang dideklarasikan dalam metode hanya ada di dalamnya; parameter hanya ada di metodenya; variabel instance terlihat di seluruh objek. Modulator akses mengontrol visibilitas melintasi kelas: private (hanya kelas ini) versus public (di mana saja). Variabel lokal menyelimuti field dengan nama yang sama – sumber bug.

    Variabel global terlihat di mana saja; variabel lokal hanya di dalam bloknya
    Variabel global terlihat di mana saja; variabel lokal hanya di dalam bloknya
    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Scope/skəʊp/ Cakupan
    3.9

    The this Keyword · ⁨Kata Kunci this⁩

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 3.9.A: Mengembangkan kode untuk ekspresi yang merujuk pada diri sendiri dan menentukan hasil dari ekspresi-ekspresi tersebut.

    • 3.9.A.1 Di dalam metode instance atau konstruktor, kata kunci this bertindak sebagai variabel khusus yang memegang referensi ke objek saat ini—objek yang metode atau konstruktornya sedang dipanggil.
    • 3.9.A.2 Kata kunci this dapat digunakan untuk melempar objek saat ini sebagai argumen dalam pemanggilan metode.
    • 3.9.A.3 Metode kelas tidak memiliki referensi this.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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.

    Bahasa Indonesia

    this adalah referensi ke objek saat ini. Gunakan ini untuk membedakan field dari parameter dengan nama yang sama, atau untuk memanggil metode lain dari objek yang sama:

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

    Keterampilan ujian: ketika parameter konstruktor atau setter memiliki nama yang sama dengan field, Anda harus menulis this.field = param – tanpa this, penugasan tersebut tidak melakukan apa-apa yang berguna.

    3.9

    Exam tips · ⁨Tips ujian⁩

    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).
    Bahasa Indonesia
    • Rancanglah dengan metode dan kelas: enkapsulasi data sebagai private fields dan tampilkan perilaku melalui metode publik.
    • Pahami perbedaan antara objek dan kelasnya, serta fakta bahwa objek dikirim berdasarkan nilai — parameter mendapatkan salinan referensinya, sehingga metode dapat mengubah state objek, tetapi menetapkan ulang parameter tidak mempengaruhi pemanggil (Java tidak memiliki pengiriman berdasarkan referensi).
    • Jelajahi array dan ArrayList dengan aman — ukurannya adalah length vs .size(), dan penghapusan selama perulangan akan menggeser indeks.
    • Jejak metode rekursif untuk menentukan hasilnya: temukan kasus basis terlebih dahulu, lalu ikuti setiap panggilan rekursif hingga nilainya kembali (menulis kode rekursif berada di luar cakupan ujian).
    • Kenali kosakata pewarisan — superclass, subclass, method overriding, dan bahwa setiap kelas adalah subclass dari Object (merancang dan mengimplementasikan pewarisan berada di luar ruang lingkup ujian).
  • 4

    Data Collections · ⁨Koleksi Data⁩

    Watch lesson · ⁨Tonton pelajaran⁩
    4.1

    The Ethics of Collecting Data

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.1.A: Menjelaskan risiko terhadap privasi dari pengumpulan dan penyimpanan data pribadi pada sistem komputer.

    • 4.1.A.1 Saat menggunakan komputer, privasi pribadi berisiko. Saat mengembangkan program baru, programmer harus berusaha melindungi privasi pribadi pengguna.

    Tujuan Pembelajaran 4.1.B: Menjelaskan pentingnya mengenali kualitas data dan potensi masalah saat menggunakan himpunan data.

    • 4.1.B.1 Bias algoritma menggambarkan kesalahan sistematis dan berulang dalam program yang menciptakan hasil yang tidak adil bagi kelompok pengguna tertentu.
    • 4.1.B.2 Programmer harus menyadari metode pengumpulan himpunan data dan potensi bias ketika menggunakan metode tersebut sebelum menggunakan data untuk mengekstrapolasi informasi baru atau menarik kesimpulan.
    • 4.1.B.3 Beberapa himpunan data tidak lengkap atau berisi data yang tidak akurat. Menggunakan data seperti itu dalam pengembangan atau penggunaan program dapat menyebabkan program bekerja secara tidak benar atau tidak efisien.

    Tujuan Pembelajaran 4.1.C: Mengidentifikasi himpunan data yang tepat untuk digunakan guna memecahkan masalah atau menjawab pertanyaan spesifik.

    • 4.1.C.1 Isi dari himpunan data mungkin berkaitan dengan pertanyaan atau topik tertentu dan mungkin tidak tepat untuk memberikan jawaban yang benar atau mengekstrapolasi informasi untuk pertanyaan atau topik lain.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    privacy/ˈprɪvəsi/ privasi
    consent/kənˈsent/ persetujuan
    bias/ˈbaɪəs/ bias
    4.2

    Why We Need Data Structures

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.2.A: Merepresentasikan pola dan algoritma yang melibatkan set data yang ditemukan dalam kehidupan sehari-hari menggunakan bahasa tulisan atau diagram.

    • 4.2.A.1 Sebuah set data adalah kumpulan piece informasi spesifik atau data.
    • 4.2.A.2 Set data dapat dimanipulasi dan dianalisis untuk memecahkan masalah atau menjawab pertanyaan. Saat menganalisis set data, nilai-nilai di dalamnya diakses dan digunakan satu per satu lalu diproses sesuai dengan hasil yang diinginkan.
    • 4.2.A.3 Data dapat direpresentasikan dalam diagram menggunakan grafik atau tabel. Visual ini dapat digunakan untuk merancang algoritma yang akan digunakan untuk memanipulasi data.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    data structure/ˈdeɪtə ˈstrʌktʃə/ struktur data
    4.3

    Making and Reading an Array

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.3.A: Mengembangkan kode yang digunakan untuk merepresentasikan koleksi data terkait menggunakan objek array satu dimensi (1D).

    • 4.3.A.1 Sebuah array menyimpan banyak nilai dari tipe yang sama. Nilainya bisa berupa nilai primitif atau referensi objek.
    • 4.3.A.2 Panjang array ditetapkan pada saat pembuatan dan tidak dapat diubah. Panjang array dapat diakses melalui atribut length.
    • 4.3.A.3 Ketika array dibuat menggunakan kata kunci new, semua elemennya diinisialisasi dengan nilai default untuk tipe data elemen. Nilai default untuk int adalah 0, untuk double adalah 0.0, untuk boolean adalah false, dan untuk tipe referensi adalah null.
    • 4.3.A.4 Daftar inisialisasi dapat digunakan untuk membuat dan menginisialisasi array.
    • 4.3.A.5 Kurung siku [ ] digunakan untuk mengakses dan memodifikasi elemen dalam array 1D menggunakan indeks.
    • 4.3.A.6 Nilai indeks yang valid untuk array adalah 0 hingga satu kurang dari panjang array, inklusif. Menggunakan nilai indeks di luar rentang ini akan menghasilkan ArrayIndexOutOfBoundsException.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    array/əˈreɪ/ array
    4.4

    Visiting Every Element of an Array

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.4.A: Mengembangkan kode yang digunakan untuk menelusuri elemen dalam array 1D dan menentukan hasil dari penelusuran tersebut.

    • 4.4.A.1 Menelusuri array adalah ketika pernyataan pengulangan digunakan untuk mengakses semua atau urutan elemen tertentu dalam array.
    • 4.4.A.2 Menelusuri array dengan loop for berbasis indeks atau loop while memerlukan elemen diakses menggunakan indeks mereka.
    • 4.4.A.3 Header loop enhanced for mencakup variabel, yang disebut sebagai variabel loop enhanced for. Untuk setiap iterasi loop enhanced for, variabel loop enhanced for diberikan salinan dari elemen tanpa menggunakan indeksnya.
    • 4.4.A.4 Memberikan nilai baru kepada variabel loop enhanced for tidak mengubah nilai yang disimpan dalam array.
    • 4.4.A.5 Ketika array menyimpan referensi objek, atribut dapat dimodifikasi dengan memanggil method pada variabel loop enhanced for. Ini tidak mengubah referensi objek yang disimpan dalam array.
    • 4.4.A.6 Kode yang ditulis menggunakan loop for yang ditingkatkan untuk menelusuri elemen dalam array dapat ditulis ulang menggunakan loop for terindeks atau loop while.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Traverse/trəˈvɜːs/ Penelusuran
    4.5

    Standard Array Algorithms

    Syllabus · ⁨Silabus⁩
    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
    Bahasa Indonesia

    Tujuan Pembelajaran 4.5.A: Mengembangkan kode untuk algoritma standar dan asli untuk konteks atau spesifikasi tertentu yang melibatkan array dan menentukan hasil dari algoritma-algoritma tersebut.

    • 4.5.A.1 Terdapat algoritma standar yang menggunakan penelusuran array untuk:
      • menentukan nilai minimum atau maksimum
      • menghitung jumlah atau rata-rata
      • menentukan apakah setidaknya satu elemen memiliki sifat tertentu
      • menentukan apakah semua elemen memiliki sifat tertentu
      • menentukan jumlah elemen yang memiliki sifat tertentu
      • mengakses semua pasangan elemen berturut-turut
      • menentukan keberadaan atau ketiadaan elemen duplikat
      • menggeser atau memutar elemen ke kiri atau kanan
      • membalik urutan elemen

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 4.6.A: Mengembangkan kode untuk membaca data dari file teks.

    • 4.6.A.1 File adalah penyimpanan data yang bertahan ketika program tidak berjalan. Data dalam file dapat diambil selama eksekusi program.
    • 4.6.A.2 File dapat dihubungkan ke program menggunakan kelas File dan Scanner.
    • 4.6.A.3 File dapat dibuka dengan membuat objek File, menggunakan nama file sebagai argumen konstruktor.
      • File(String str) adalah konstruktor File yang menerima nama file String untuk dibuka untuk pembacaan, di mana str adalah path nama untuk file tersebut.
    • 4.6.A.4 Saat menggunakan kelas File, diperlukan untuk menunjukkan apa yang harus dilakukan jika file dengan nama yang diberikan tidak dapat dibuka. Salah satu cara untuk mencapai hal ini adalah dengan menambahkan throws IOException ke header metode yang menggunakan file. Jika nama file tidak valid, program akan berhenti.
    • 4.6.A.5 Kelas File dan IOException merupakan bagian dari paket java.io. Pernyataan import harus digunakan agar kelas-kelas ini tersedia untuk digunakan dalam program.
    • 4.6.A.6 Metode Scanner dan konstruktor berikut—termasuk apa yang mereka lakukan dan kapan mereka digunakan—merupakan bagian dari Referensi Cepat Java:
      • Scanner(File f) adalah konstruktor Scanner yang menerima File untuk dibaca.
      • int nextInt() mengembalikan int berikutnya yang dibaca dari file atau sumber input jika tersedia. Jika int berikutnya tidak ada atau berada di luar jangkauan, hal itu akan menghasilkan InputMismatchException.
      • double nextDouble() mengembalikan double berikutnya yang dibaca dari file atau sumber input. Jika double berikutnya tidak ada, hal itu akan menghasilkan InputMismatchException.
      • boolean nextBoolean() mengembalikan boolean berikutnya yang dibaca dari file atau sumber input. Jika boolean berikutnya tidak ada, hal itu akan menghasilkan InputMismatchException.
      • String nextLine() mengembalikan baris teks berikutnya sebagai String yang dibaca dari file atau sumber input; dapat mengembalikan string kosong jika dipanggil segera setelah metode Scanner lain yang sedang membaca dari file atau sumber input.
      • String next() mengembalikan String berikutnya yang dibaca dari file atau sumber input.
      • boolean hasNext() mengembalikan true jika ada item berikutnya untuk dibaca di file atau sumber input; mengembalikan false jika tidak.
      • void close() menutup scanner ini.
      • Pengecualian: Menerima input dari keyboard berada di luar cakupan kursus AP Computer Science A dan ujian.
    • 4.6.A.7 Menggunakan nextLine dan metode Scanner lainnya bersama-sama pada sumber input yang sama terkadang memerlukan kode untuk menyesuaikan diri dengan cara berbeda dari metode-metode tersebut dalam menangani spasi putih.
      • Pengecualian: Menulis atau menganalisis kode yang menggunakan baik nextLine maupun metode Scanner lainnya pada sumber input yang sama berada di luar cakupan kursus AP Computer Science A dan ujian.
    • 4.6.A.8 Metode String tambahan berikut—termasuk apa yang ia lakukan dan kapan ia digunakan—merupakan bagian dari Referensi Cepat Java:
      • String[] split(String del) mengembalikan array String di mana setiap elemen adalah substring dari this String, yang telah dipisahkan berdasarkan kecocokan dari ekspresi yang diberikan del.
      • Pengecualian: Parameter del menggunakan format yang disebut ekspresi reguler. Menulis atau menganalisis kode yang menggunakan salah satu sifat khusus dari ekspresi reguler (mis., \\*, \\.) berada di luar cakupan kursus AP Computer Science A dan ujian.
    • 4.6.A.9 Loop while dapat digunakan untuk mendeteksi apakah file masih berisi elemen yang dapat dibaca dengan menggunakan metode hasNext sebagai kondisi loop.
    • 4.6.A.10 File harus ditutup ketika program selesai menggunakannya. Metode close dari Scanner dipanggil untuk menutup file.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.7.A: Mengembangkan kode untuk menggunakan objek Integer dan Double dari tipe primitifnya dan menentukan hasil penggunaan objek-objek tersebut.

    • 4.7.A.1 Kelas Integer dan kelas Double merupakan bagian dari paket java.lang. Objek Integer bersifat tidak dapat diubah, artinya setelah objek Integer dibuat, atributnya tidak dapat diubah. Objek Double bersifat tidak dapat diubah, artinya setelah objek Double dibuat, atributnya tidak dapat diubah.
    • 4.7.A.2 Autoboxing adalah konversi otomatis yang dilakukan oleh compiler Java antara tipe primitif dan kelas pembungkus objek yang sesuai. Ini termasuk mengkonversi int menjadi Integer dan double menjadi Double. Compiler Java menerapkan autoboxing ketika nilai primitif:
      • dilewatkan sebagai parameter ke metode yang mengharapkan objek dari kelas pembungkus yang sesuai
      • ditugaskan ke variabel dari kelas pembungkus yang sesuai
    • 4.7.A.3 Unboxing adalah konversi otomatis yang dilakukan oleh compiler Java dari kelas pembungkus ke tipe primitif. Ini termasuk mengkonversi Integer menjadi int dan Double menjadi double. Compiler Java menerapkan unboxing ketika objek kelas pembungkus:
      • dilewatkan sebagai parameter ke metode yang mengharapkan nilai dari tipe primitif yang sesuai
      • ditugaskan ke variabel dari tipe primitif yang sesuai
    • 4.7.A.4 Metode Integer kelas berikut—termasuk apa yang ia lakukan dan kapan ia digunakan—merupakan bagian dari Referensi Cepat Java:
      • static int parseInt(String s) mengembalikan argumen String sebagai int.
    • 4.7.A.5 Metode Double kelas berikut—termasuk apa yang ia lakukan dan kapan ia digunakan—merupakan bagian dari Referensi Cepat Java:
      • static double parseDouble(String s) mengembalikan argumen String sebagai double.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    autoboxing/ˌɔːtəʊˈbɒksɪŋ/ autoboxing
    4.8

    The ArrayList Toolbox

    Syllabus · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 4.8.A: Mengembangkan kode untuk koleksi objek terkait menggunakan objek ArrayList dan menentukan hasil pemanggilan metode pada objek-objek tersebut.

    • 4.8.A.1 Objek ArrayList dapat diubah ukurannya dan berisi referensi objek.
    • 4.8.A.2 Konstruktor ArrayList ArrayList() membuat daftar kosong.
    • 4.8.A.3 Java mengizinkan tipe generik ArrayList<E>, di mana parameter tipe E menentukan tipe elemen. Ketika ArrayList<E> ditentukan, tipe dari parameter referensi dan tipe kembali saat menggunakan metode ArrayList adalah tipe E. ArrayList<E> lebih disukai daripada ArrayList. Sebagai contoh, ArrayList<String> names = new ArrayList<String>(); memungkinkan compiler untuk menemukan error yang akan ditemukan pada waktu run-time jika tidak ada.
    • 4.8.A.4 Kelas ArrayList merupakan bagian dari paket java.util. Pernyataan import import harus digunakan agar kelas ini tersedia untuk digunakan dalam program.
    • 4.8.A.5 Metode ArrayList berikut—termasuk fungsi dan penggunaannya—merupakan bagian dari Rujukan Cepat Java:
      • int size() mengembalikan jumlah elemen dalam daftar.
      • boolean add(E obj) menambahkan obj ke akhir daftar; mengembalikan true.
      • void add(int index, E obj) menyisipkan obj pada posisi index (0 <= index <= size), memindahkan elemen pada posisi index dan lebih tinggi ke kanan (menambahkan 1 ke indeks mereka) dan menambahkan 1 ke ukuran.
      • E get(int index) mengembalikan elemen pada posisi index dalam daftar.
      • E set(int index, E obj) mengganti elemen pada posisi index dengan obj; mengembalikan elemen yang sebelumnya berada di posisi index.
      • E remove(int index) menghapus elemen dari posisi index, memindahkan elemen pada posisi index + 1 dan lebih tinggi ke kiri (mengurangi 1 pada indeks mereka) dan mengurangi 1 pada ukuran; mengembalikan elemen yang sebelumnya berada di posisi index.
    • 4.8.A.6 Indeks untuk ArrayList dimulai dari 0 dan berakhir pada jumlah elemen - 1.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    ArrayList/əˈreɪ lɪst/ ArrayList
    4.9

    Visiting Every Element of an ArrayList

    Syllabus · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 4.9.A: Mengembangkan kode yang digunakan untuk menelusuri elemen dari ArrayList dan menentukan hasil pelayaran tersebut.

    • 4.9.A.1 Menelusuri ArrayList adalah ketika pernyataan iterasi atau rekursif digunakan untuk mengakses semua atau urutan elemen tertentu dalam ArrayList.
    • 4.9.A.2 Menghapus elemen selama penelusuran ArrayList memerlukan penggunaan teknik khusus untuk menghindari melewatkan elemen.
    • 4.9.A.3 Mencoba mengakses nilai indeks di luar rentangnya akan menghasilkan IndexOutOfBoundsException.
    • 4.9.A.4 Mengubah ukuran ArrayList selama menelusurinya menggunakan loop for diperluas dapat menghasilkan ConcurrentModificationException. Oleh karena itu, ketika menggunakan loop for diperluas untuk menelusuri ArrayList, Anda tidak boleh menambahkan atau menghapus elemen.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.10.A: Mengembangkan kode untuk algoritma standar dan orisinal untuk konteks atau spesifikasi tertentu yang melibatkan objek ArrayList dan menentukan hasil dari algoritma-algoritma tersebut.

    • 4.10.A.1 Terdapat algoritma ArrayList standar yang memanfaatkan penelusuran untuk:
      • menentukan nilai minimum atau maksimum
      • menghitung jumlah atau rata-rata
      • menentukan apakah setidaknya satu elemen memiliki sifat tertentu
      • menentukan apakah semua elemen memiliki sifat tertentu
      • menentukan jumlah elemen yang memiliki sifat tertentu
      • mengakses semua pasangan elemen berturut-turut
      • menentukan keberadaan atau ketiadaan elemen duplikat
      • menggeser atau memutar elemen ke kiri atau kanan
      • membalik urutan elemen
      • menyisipkan elemen
      • menghapus elemen
    • 4.10.A.2 Beberapa algoritma memerlukan beberapa String, array, atau objek ArrayList ditelusuri secara bersamaan.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 · ⁨Silabus⁩
    English

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

    Tujuan Pembelajaran 4.11.A: Mengembangkan kode yang digunakan untuk merepresentasikan kumpulan data yang saling terkait menggunakan objek array dua dimensi (2D).

    • 4.11.A.1 Array 2D disimpan sebagai array dari array. Oleh karena itu, cara pembuatan dan pengindeksan array 2D mirip dengan objek array 1D. Ukuran array 2D ditetapkan saat pembuatan dan tidak dapat diubah. Array 2D dapat menyimpan data primitif atau data referensi objek.
      • Pernyataan pengecualian: Objek array 2D non-rectangular berada di luar cakupan mata kuliah dan ujian AP Computer Science A.
    • 4.11.A.2 Ketika array 2D dibuat menggunakan kata kunci new, semua elemennya diinisialisasi dengan nilai default untuk tipe data elemen. Nilai default untuk int adalah 0, untuk double adalah 0.0, untuk boolean adalah false, dan untuk tipe referensi adalah null.
    • 4.11.A.3 Daftar inisialisasi yang digunakan untuk membuat dan menginisialisasi array 2D terdiri dari daftar inisialisasi yang merepresentasikan array 1D; misalnya, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };.
    • 4.11.A.4 Tanda kurung siku [row][col] digunakan untuk mengakses dan memodifikasi elemen dalam array 2D. Untuk tujuan ujian, saat mengakses elemen pada arr[first][second], indeks pertama digunakan untuk baris, indeks kedua digunakan untuk kolom.
    • 4.11.A.5 Satu array tunggal yang merupakan baris dari array 2D dapat diakses menggunakan nama array 2D dan satu set tanda kurung siku yang berisi indeks baris.
    • 4.11.A.6 Jumlah baris yang terkandung dalam array 2D dapat diakses melalui atribut length. Nilai indeks baris yang valid untuk array 2D adalah 0 hingga satu kurang dari jumlah baris atau panjang array, termasuk. Jumlah kolom yang terkandung dalam array 2D dapat diakses melalui atribut length dari salah satu baris. Nilai indeks kolom yang valid untuk array 2D adalah 0 hingga satu kurang dari jumlah kolom atau panjang setiap baris tertentu dari array, termasuk. Sebagai contoh, diberikan array 2D bernama values, jumlah baris adalah values.length dan jumlah kolom adalah values[0].length. Menggunakan nilai indeks di luar rentang ini akan menghasilkan ArrayIndexOutOfBoundsException.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Jelajahi⁩

    Index a 2D array by row and column · ⁨Indeks array 2D berdasarkan baris dan kolom⁩

    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. · ⁨Array 2D adalah grid yang dialamatkan oleh [row][col]. Gerakkan indeks dan lihat sel mana yang mereka pilih — baris dulu, lalu kolom, keduanya dihitung dari 0.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    2D array/ˌtuː ˈdiː əˈreɪ/ array 2D
    4.12

    Walking Through a Grid

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.12.A: Mengembangkan kode yang digunakan untuk menelusuri elemen dalam array 2D dan menentukan hasil penelusuran tersebut.

    • 4.12.A.1 Pernyataan iterasi bersarang digunakan untuk menelusuri dan mengakses semua atau urutan elemen tertentu dalam array 2D. Karena array 2D disimpan sebagai array dari array, cara array 2D ditelusuri menggunakan loop for dan loop enhanced for mirip dengan objek array 1D. Pernyataan iterasi bersarang dapat ditulis untuk menelusuri array 2D secara urutan baris (row-major order), urutan kolom (column-major order), atau urutan yang terdefinisi secara unik. Urutan baris merujuk pada pengurutan elemen array 2D di mana penelusuran terjadi melintasi setiap baris, sedangkan penelusuran urutan kolom terjadi ke bawah setiap kolom.
    • 4.12.A.2 Loop luar dari loop enhanced for bersarang yang digunakan untuk menelusuri array 2D menelusuri baris-barisnya. Oleh karena itu, variabel loop enhanced for harus bertipe seperti setiap baris, yaitu array 1D. Loop dalam menelusuri satu baris tunggal. Oleh karena itu, variabel loop enhanced for dalam harus memiliki tipe yang sama dengan elemen yang disimpan dalam array 1D. Menetapkan nilai baru pada variabel loop enhanced for tidak mengubah nilai yang tersimpan dalam array.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    row-major order/rəʊ ˈmeɪdʒə ˈɔːdə/ urutan baris-utama
    4.13

    Standard 2D Array Algorithms

    Syllabus · ⁨Silabus⁩
    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
    Bahasa Indonesia

    Tujuan Pembelajaran 4.13.A: Mengembangkan kode untuk algoritma standar dan orisinal untuk konteks atau spesifikasi tertentu yang melibatkan array 2D dan menentukan hasil algoritma-algoritma tersebut.

    • 4.13.A.1 Terdapat algoritma standar yang menggunakan penelusuran array 2D untuk:
      • menentukan nilai minimum atau maksimum dari semua elemen atau untuk baris, kolom, atau subbagian yang ditentukan
      • menghitung jumlah atau rata-rata dari semua elemen atau untuk baris, kolom, atau subbagian yang ditentukan
      • menentukan apakah setidaknya satu elemen memiliki sifat tertentu di seluruh array 2D atau untuk baris, kolom, atau subbagian yang ditentukan
      • menentukan apakah semua elemen array 2D atau baris, kolom, atau subbagian yang ditentukan memiliki sifat tertentu
      • menentukan jumlah elemen dalam array 2D atau dalam baris, kolom, atau subbagian yang ditentukan yang memiliki sifat tertentu
      • mengakses semua pasangan elemen berturut-turut
      • menentukan keberadaan atau ketiadaan elemen duplikat dalam array 2D atau dalam baris, kolom, atau subbagian yang ditentukan
      • menggeser atau memutar elemen dalam sebuah baris ke kiri atau ke kanan atau dalam sebuah kolom ke atas atau ke bawah
      • membalik urutan elemen dalam sebuah baris atau kolom

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian 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 · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.14.A: Mengembangkan kode yang digunakan untuk algoritma pencarian linear untuk mencari informasi spesifik dalam kumpulan data dan menentukan hasil eksekusi pencarian.

    • 4.14.A.1 Algoritma pencarian linear adalah algoritma standar yang memeriksa setiap elemen secara berurutan hingga nilai yang diinginkan ditemukan atau semua elemen dalam array atau ArrayList telah diperiksa. Algoritma pencarian linear dapat memulai proses pencarian dari salah satu ujung array atau ArrayList.
    • 4.14.A.2 Saat menerapkan algoritma pencarian linear pada array 2D, setiap baris harus diakses terlebih dahulu kemudian pencarian linear diterapkan pada setiap baris dari array 2D.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Jelajahi⁩

    Compare linear and binary search · ⁨Bandingkan pencarian linear dan biner⁩

    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. · ⁨Pencarian linear memeriksa setiap elemen secara bergantian; pencarian biner membagi dua daftar terurut setiap langkah. Lihat pencarian biner mencapai target dalam jauh lebih sedikit perbandingan.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Linear search/ˈlɪnɪə sɜːtʃ/ Pencarian linear
    Binary search/ˈbaɪnəri sɜːtʃ/ Pencarian biner
    4.15

    Putting Data in Order: Selection and Insertion Sort

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.15.A: Menentukan hasil eksekusi setiap langkah algoritma pengurutan untuk mengurutkan elemen dalam suatu kumpulan data.

    • 4.15.A.1 Selection sort dan insertion sort adalah algoritma pengurutan iteratif yang dapat digunakan untuk mengurutkan elemen dalam array atau ArrayList.
    • 4.15.A.2 Selection sort secara berulang memilih elemen terkecil (atau terbesar) dari bagian daftar yang belum terurut dan menukarnya ke posisi yang benar (dan akhir) di bagian daftar yang sudah terurut.
    • 4.15.A.3 Sortir sisipan menyisipkan elemen dari bagian yang belum terurut dalam daftar ke posisi yang benar (tetapi tidak necessarily final) di bagian yang sudah terurut dengan menggeser elemen-elemen dari bagian yang sudah terurut untuk memberi ruang bagi elemen baru.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Jelajahi⁩

    Watch a sorting algorithm order a list · ⁨Lihat algoritma penyortiran mengurutkan daftar⁩

    A sort rearranges elements into order. Step through selection/insertion sort to see the sorted region grow one element at a time. · ⁨Sortir menyusun ulang elemen menjadi tertib. Telusuri seleksi/insertion sort untuk melihat wilayah terurut bertambah satu elemen pada satu waktu.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Selection sort/sɪˈlekʃn sɔːt/ Selection sort
    Insertion sort/ɪnˈsɜːʃn sɔːt/ Insertion sort
    4.16

    Methods That Call Themselves: Recursion

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.16.A: Menentukan hasil dari pemanggilan metode rekursif.

    • 4.16.A.1 Sebuah metode rekursif adalah metode yang memanggil dirinya sendiri. Metode rekursif mengandung setidaknya satu kasus dasar, yang menghentikan rekursi, dan setidaknya satu panggilan rekursif. Rekursi adalah bentuk pengulangan lain.
    • 4.16.A.2 Setiap panggilan rekursif memiliki set variabel lokal masing-masing, termasuk parameter. Nilai parameter menangkap kemajuan proses rekursif, mirip seperti nilai variabel kontrol perulangan menangkap kemajuan sebuah loop.
    • 4.16.A.3 Setiap solusi rekursif dapat direplikasi melalui penggunaan pendekatan iteratif dan sebaliknya.
      • Pernyataan Pengecualian: Penulisan kode rekursif berada di luar cakupan kursus dan ujian AP Computer Science A.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Jelajahi⁩

    Unfold a recursive call · ⁨Buka pemanggilan rekursif⁩

    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. · ⁨Metode rekursif memanggil dirinya sendiri pada input yang lebih kecil hingga mencapai kasus dasar, kemudian hasilnya melipat naik kembali. Telusuri untuk melihat tumpukan pemanggilan dan pembukaannya.⁩

    Vocabulary · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Recursion/rɪˈkɜːʃn/ Recursion
    base case/beɪs keɪs/ kasus dasar
    4.17

    Recursive Search and Merge Sort

    Syllabus · ⁨Silabus⁩
    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.
    Bahasa Indonesia

    Tujuan Pembelajaran 4.17.A: Menentukan hasil dari eksekusi algoritma rekursif yang menggunakan string atau koleksi.

    • 4.17.A.1 Rekursi dapat digunakan untuk menelusuri String objek, array, dan ArrayList objek.

    Tujuan Pembelajaran 4.17.B: Menentukan hasil dari setiap iterasi algoritma pencarian biner yang digunakan untuk mencari informasi dalam sebuah koleksi.

    • 4.17.B.1 Data harus dalam urutan terurut untuk menggunakan algoritma pencarian biner. Pencarian biner dimulai dari tengah array terurut atau ArrayList dan menghilangkan separuh dari array atau ArrayList dalam setiap panggilan rekursif hingga nilai yang diinginkan ditemukan atau semua elemen telah dihilangkan.
    • 4.17.B.2 Pencarian biner biasanya lebih efisien daripada pencarian linear.
      • Pernyataan Pengecualian: Algoritma pencarian selain pencarian linear dan biner berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 4.17.B.3 Algoritma pencarian biner dapat ditulis baik secara iteratif maupun rekursif.

    Tujuan Pembelajaran 4.17.C: Menentukan hasil dari setiap iterasi algoritma merge sort ketika digunakan untuk mengurutkan sebuah koleksi.

    • 4.17.C.1 Merge sort adalah algoritma pengurutan rekursif yang dapat digunakan untuk mengurutkan elemen dalam array atau ArrayList.
      • Pernyataan Pengecualian: Algoritma pengurutan selain selection, insertion, dan merge sort berada di luar cakupan kursus dan ujian AP Computer Science A.
    • 4.17.C.2 Merge sort berulang kali membagi array menjadi subarray yang lebih kecil hingga setiap subarray berisi satu elemen dan kemudian secara rekursif menggabungkan subarray yang sudah terurut kembali bersama-sama dalam urutan terurut untuk membentuk array akhir yang terurut.

    Source: College Board AP Course and Exam Description · ⁨Sumber: Deskripsi Kursus dan Ujian College Board AP⁩

    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 · ⁨Kosa kata⁩ Train · ⁨Latih⁩
    English Bahasa Indonesia
    Merge sort/mɜːdʒ sɔːt/ Sortir gabung
    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 · ⁨Masuk atau buat akun⁩

IGCSE, A-Level & AP