ข้ามไปยังเนื้อหา
รายวิชา
  • 1 พื้นฐาน Java
    1.1

    คลาส (Classes), main และ output

    This site compiles Java using Java 8 language rules. These standalone examples put their entry method, main, inside a class. Helper classes and method-only answers do not need their own main. System.out.println(...) prints a line; System.out.print(...) prints with no new line.

    public class Main {
        public static void main(String[] args) {
            System.out.println("Hello, world!");
            System.out.println("I am learning Java.");
        }
    }
    
    • Java เป็นภาษาที่ compile:编译器ตรวจสอบทั้งโปรแกรมก่อน แล้วจึงรัน.
    • การประกาศ การกำหนดค่า การเรียก method และ return สโตเมนต์ลงท้ายด้วยเครื่องหมายคั่นคำ ; บล็อก if, for หรือ while ใช้วงเล็บปีกกา; อย่าเพิ่มเครื่องหมายคั่นคำเพราะมีวงเล็บปิด
    ตัวอย่าง Java 8 แบบสแตนด์อโลนนี้กำหนด main ไว้ภายในคลาส
    ตัวอย่าง Java 8 แบบสแตนด์อโลนนี้กำหนด main ไว้ภายในคลาส
    1.2

    ตัวแปรและชนิดข้อมูลพื้นฐาน (Variables & primitive types)

    ตัวแปรต้องประกาศชนิดของมัน ชนิดพื้นฐานทั่วไป: int (จำนวนเต็ม), double (ทศนิยม), boolean (true/false), char (ตัวอักษรหนึ่งตัว)

    public class Main {
        public static void main(String[] args) {
            int age = 17;
            double price = 9.99;
            boolean passed = true;
            System.out.println(age + " " + price + " " + passed);
        }
    }
    
    1.3

    Comments & style

    Comment คือ // (หนึ่งบรรทัด) หรือ /* ... */ (block). จัดระยะย่อโค้ดภายในวงเล็บ curly { }. ชื่อคลาสเริ่มด้วยตัวพิมพ์ใหญ่; ตัวแปรและใช้ camelCase (ตัวเล็กเป็นต้น).

    public class Main {
        public static void main(String[] args) {
            // greet the user
            String firstName = "Mei";
            System.out.println("Hi, " + firstName);
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • คำสั่งทุกอันลงท้ายด้วยเครื่องหมายกึ่งทวิภาค ;.
    • main ต้องเป็น public static void main(String[] args) อย่างแม่นยำ
    • println เพิ่มบรรทัดใหม่; print ไม่เพิ่ม.
  • 2 ตัวดำเนินการ &-expression
    2.1

    การคำนวณและการกำหนดค่า (Arithmetic & assignment)

    การคำนวณใน Java ใช้ + - * / และ % (เศษเหลือ). เมื่อใช้สอง ints, / เป็นการหารแบบ integer — จะตัดทศนิยมออก. +=, -=, และ ++ เป็นทางลัด.

    public class Main {
        public static void main(String[] args) {
            int a = 7, b = 2;
            System.out.println(a / b);    // 3 (integer division)
            System.out.println(a % b);    // 1
            double x = 7.0 / 2;           // 3.5 (one side is double)
            System.out.println(x);
        }
    }
    
    int/int truncates; involve a double for a real quotient
    int/int ตัดเศษ; ต้องใช้ double เพื่อผลลัพธ์จริง
    2.2

    การใช้ objects: String, Math, wrappers

    บางค่าคือ objects ที่มี methods. String มี .length(), .substring(), .toUpperCase(). Math มี Math.max, Math.sqrt, Math.pow. Wrapper classes (Integer, Double) ห่อหุ้ม primitive — เช่น Integer.parseInt("42").

    public class Main {
        public static void main(String[] args) {
            String s = "Hello";
            System.out.println(s.length());                  // 5
            System.out.println(s.toUpperCase());             // HELLO
            System.out.println(Math.max(3, 9));              // 9
            System.out.println(Integer.parseInt("42") + 1);  // 43
        }
    }
    

    Math.random() คืนค่า random double จาก 0.0 ไปจนถึง (แต่ไม่รวม) 1.0. ขยายสเกลและ cast เพื่อได้จำนวนเต็ม — นี่คือ AP idiom:

    public class Main {
        public static void main(String[] args) {
            // a random whole number from 1 to 6 (a dice roll)
            int roll = (int) (Math.random() * 6) + 1;
            System.out.println(roll >= 1 && roll <= 6);   // true
        }
    }
    
    • Integer.MAX_VALUE (2147483647) และ Integer.MIN_VALUE เป็นขอบเขตของ int; หากเกินขอบเขตนี้จะวนกลับ (overflow).
    • ตัวแปร object ที่ชี้ไปยัง object ใดไม่อยู่จะถือ null; การเรียก method บนมันจะเกิด NullPointerException.
    2.3

    การ cast และการแปลงชนิด (Casting & type conversion)

    Cast เปลี่ยนชนิดของค่า. (int) ตัดทศนิยมออก; (double) หลีกเลี่ยงการหารแบบ integer เมื่อต้องการผลลัพธ์ที่แม่นยำ.

    public class Main {
        public static void main(String[] args) {
            double pi = 3.99;
            System.out.println((int) pi);            // 3
            int total = 7, n = 2;
            System.out.println((double) total / n);  // 3.5
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • การหารแบบ integer: 5 / 2 เป็น 2, ไม่ใช่ 2.5. Cast ก่อน: (double) 5 / 2.
    • เปรียบเทียบ Strings (และ object อื่นๆ) ด้วย .equals() ไม่ใช่ ==
    • == on two objects tests whether they are the SAME object, not whether they look equal.
  • 3 Booleans & selection
    3.1

    if / else

    if รัน block เมื่อเงื่อนไขเป็นจริง; else if และ else เพิ่มกรณีอื่นๆ. เงื่อนไขอยู่ใน ( ), block อยู่ใน { }.

    public class Main {
        public static void main(String[] args) {
            int score = 72;
            if (score >= 80) {
                System.out.println("A");
            } else if (score >= 60) {
                System.out.println("B");
            } else {
                System.out.println("fail");
            }
        }
    }
    
    if เลือกทางที่จริง; else เลือกทางที่เท็จ
    if เลือกทางที่จริง; else เลือกทางที่เท็จ
    3.2

    Logic operators & comparisons

    เปรียบเทียบด้วย ==, !=, <, >, <=, >= — การเปรียบเทียบคืนค่า boolean. รวมด้วย && (and), || (or), ! (not) — logical operators. สำหรับ Strings, ใช้ .equals(...), ไม่ใช่ ==.

    public class Main {
        public static void main(String[] args) {
            int age = 16;
            boolean member = true;
            System.out.println(age >= 18 && member);   // false
            String a = "hi";
            System.out.println(a.equals("hi"));        // true
        }
    }
    
    3.3

    สวิตช์

    switch เลือกจากหลายค่าที่กำหนดไว้. แต่ละ case ลงท้ายด้วย break; default เป็นค่าสำรอง.

    public class Main {
        public static void main(String[] args) {
            int day = 3;
            switch (day) {
                case 1: System.out.println("Mon"); break;
                case 3: System.out.println("Wed"); break;
                default: System.out.println("other");
            }
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • เงื่อนไขต้องเป็น boolean; if (x = 5) ไม่ compile (ใช้ ==).
    • แต่ละ switch case ต้องมี break;, ถ้าไม่มี control จะไหลไป case ถัดไป.
    • && และ || เป็น logical operators; & และ | เป็น bitwise.
  • 4 Loops
    4.1

    ลูป while

    while ลูปจะซ้ำwhileเงื่อนไขเป็นจริง เปลี่ยนแปลงบางอย่างภายในหรือมันจะวนลูปตลอดไป

    public class Main {
        public static void main(String[] args) {
            int n = 1;
            while (n <= 3) {
                System.out.println(n);
                n++;
            }
        }
    }
    
    while ตรวจสอบเงื่อนไขก่อนแต่ละรอบของบอดี้
    while ตรวจสอบเงื่อนไขก่อนแต่ละรอบของบอดี้
    4.2

    ลูป for

    A for loop บรรจุการเริ่มต้น, เงื่อนไข, และขั้นตอนในบรรทัดเดียว. ดีที่สุดเมื่อคุณทราบจำนวนรอบ.

    public class Main {
        public static void main(String[] args) {
            for (int i = 0; i < 5; i++) {
                System.out.print(i + " ");
            }
            System.out.println();   // 0 1 2 3 4
        }
    }
    
    4.3

    Accumulation

    Accumulator pattern: เริ่มตัวแปรก่อน loop, แล้วอัปเดตมันในแต่ละรอบ.

    public class Main {
        public static void main(String[] args) {
            int total = 0;
            for (int i = 1; i <= 5; i++) {
                total += i;
            }
            System.out.println(total);   // 15
        }
    }
    
    4.4

    Nested loops

    Loop Within a loop คือ nested loop. Inner loop รันเต็มรูปแบบในแต่ละรอบของ outer loop.

    public class Main {
        public static void main(String[] args) {
            for (int r = 0; r < 3; r++) {
                for (int c = 0; c < 3; c++) {
                    System.out.print("*");
                }
                System.out.println();
            }
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • for (int i = 0; i < n; i++) รัน n ครั้ง (0 ถึง n - 1); การใช้ <= จะรันเพิ่มอีกหนึ่งครั้ง.
    • อย่าใส่เครื่องหมายกึ่งทวิภาคต่อท้าย for (...) หรือ while (...) — มันจะทำให้เกิด empty loop.
    • ประกาศตัวนับใน header ของ for เพื่อให้ scope สิ้นสุดพร้อม loop.
  • 5 สตริง (Strings)
    5.1

    String methods

    String คือข้อความ วิธีการที่มีประโยชน์: .length(), .charAt(i), .substring(a, b), .indexOf(x), .toUpperCase(), .equals(...). String เป็น immutability — แต่ละวิธีคืนค่า new String

    public class Main {
        public static void main(String[] args) {
            String s = "Python";
            System.out.println(s.length());          // 6
            System.out.println(s.charAt(0));         // P
            System.out.println(s.substring(0, 3));   // Pyt
            System.out.println(s.toUpperCase());     // PYTHON
        }
    }
    

    Methods ที่คุณจะใช้ทุกวัน:

    Method ความหมาย ตัวอย่าง → ผลลัพธ์
    .length() จำนวน字符 "Hi".length() → 2
    .charAt(i) ตัวอักษรเดียว "Hi".charAt(0) → H
    .substring(a, b) ส่วน, หยุดก่อน b "Python".substring(0, 3) → Pyt
    .substring(a) จาก a ไปจนจบ "Python".substring(3) → hon
    .indexOf(x) ตำแหน่งแรก, -1 ถ้าไม่มี "banana".indexOf("na") → 2
    .equals(s) ข้อความเดียวกัน? "hi".equals("hi") → true
    .compareTo(s) ลำดับ: ลบ / 0 / บวก "apple".compareTo("banana") → ลบ

    compareTo เรียงลำดับ String ตามลำดับพจนานุกรม — การสอบ AP ใช้วิธีการนี้ในการเรียงลำดับคำถาม:

    public class Main {
        public static void main(String[] args) {
            String a = "apple", b = "banana";
            System.out.println(a.compareTo(b) < 0);    // true (apple comes first)
            System.out.println(a.compareTo("apple"));  // 0 (equal)
        }
    }
    
    Key String methods: length, charAt, substring, equals
    Key String methods: length, charAt, substring, equals
    5.2

    การสร้างและ traversing strings

    เชื่อมสตริงด้วย + (การต่อสตริง) เข้าถึงแต่ละตัวอักษรด้วยการวนซ้ำและ .charAt(i)

    public class Main {
        public static void main(String[] args) {
            String word = "banana";
            int count = 0;
            for (int i = 0; i < word.length(); i++) {
                if (word.charAt(i) == 'a') count++;
            }
            System.out.println(count);   // 3
        }
    }
    

    เมื่อสร้าง long String ใน loop, StringBuilder เร็วกว่ามาก: append pieces, แล้ว call .toString() หนึ่งครั้ง.

    public class Main {
        public static void main(String[] args) {
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= 5; i++) {
                sb.append(i).append(" ");
            }
            System.out.println(sb.toString().trim());   // 1 2 3 4 5
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • Strings are immutable: s.toUpperCase() return a new String, ดังนั้นเก็บผลลัพธ์.
    • อ่าน character ด้วย s.charAt(i); ความยาวคือ s.length() (method, with ()).
    • การสร้าง String ด้วย += ใน big loop ช้า; ใช้ StringBuilder.
  • 6 Arreglo
    6.1

    อาเรย์ 1 มิติ

    Array เก็บจำนวนคงที่ของค่าชนิดเดียวกัน. Index จาก 0, ได้ขนาดด้วย .length.

    public class Main {
        public static void main(String[] args) {
            int[] scores = {88, 71, 95};
            System.out.println(scores[0]);       // 88
            System.out.println(scores.length);   // 3
            scores[1] = 100;
            System.out.println(scores[1]);       // 100
        }
    }
    
    ค่าพื้นฐานจะคงค่าไว้; ตัวแปรอาร์เรย์จะเก็บอ้างอิงไปยังวัตถุอาร์เรย์
    ค่าพื้นฐานจะคงค่าไว้; ตัวแปรอาร์เรย์จะเก็บอ้างอิงไปยังวัตถุอาร์เรย์
    6.2

    อัลกอริทึมอาเรย์

    ใช้ลูปวนผ่านอาร์เรย์เพื่อหาค่าสูงสุด, ผลรวม, จำนวน หรือค้นหา ค่า for (int x : a) (for-each loop) จะอ่านค่าแต่ละตัวตามลำดับ

    public class Main {
        public static void main(String[] args) {
            int[] a = {3, 9, 2, 7};
            int max = a[0], total = 0;
            for (int x : a) {
                if (x > max) max = x;
                total += x;
            }
            System.out.println(max + " " + total);   // 9 21
        }
    }
    
    6.3

    อาเรย์ 2 มิติ

    อาร์เรย์ 2 มิติคือตารางของแถวและหลัก: grid[row][col]

    public class Main {
        public static void main(String[] args) {
            int[][] grid = {{1, 2, 3}, {4, 5, 6}};
            System.out.println(grid[1][2]);   // 6
            for (int[] row : grid) {
                for (int v : row) System.out.print(v + " ");
            }
            System.out.println();             // 1 2 3 4 5 6
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • ขนาดของอาร์เรย์คือ a.length (ไม่มีวงเล็บ, ไม่มี ()), และจะคงที่ตั้งแต่สร้างเสร็จแล้ว
    • ดัชนีที่ใช้ได้คือ 0 ถึง a.length - 1; การเข้าถึงที่เกินจะทำให้เกิด a[a.length] ArrayIndexOutOfBoundsException
    • int[5] ใหม่จะถูกเติมด้วยเลขศูนย์ ไม่ใช่ทิ้งว่างไว้
  • 7 ArrayList
    7.1

    พื้นฐานของ ArrayList

    ArrayList คือรายการที่ยืดหดขนาดได้ — ขยายหรือหดเมื่อเพิ่มหรือลบไอเท็ม เก็บข้อมูลเป็นออบเจกต์ ดังนั้นต้องใช้ชนิด Wrapper เช่น Integer (ไม่ใช่ int) ส่วน <Integer> เป็นชนิดแบบ Generic วิธีสำคัญ: .add(x), .get(i), .set(i, x), .size(), .remove(i)

    import java.util.ArrayList;
    
    public class Main {
        public static void main(String[] args) {
            ArrayList<Integer> nums = new ArrayList<Integer>();
            nums.add(10);
            nums.add(20);
            nums.add(30);
            System.out.println(nums.size());   // 3
            System.out.println(nums.get(1));   // 20
            nums.set(0, 99);
            System.out.println(nums);          // [99, 20, 30]
        }
    }
    
    ArrayList: add, get, size on a resizable list
    ArrayList: add, get, size on a resizable list
    7.2

    อัลกอริทึมของ ArrayList & บักการลบ

    .remove(i) จะเลื่อนองค์ประกอบถัดไปทั้งหมดไปทางซ้ายหนึ่งตำแหน่ง หากคุณลบขณะนับ i ขึ้น จะข้ามองค์ประกอบถัดไปไป การแก้ไข: ลูป ถอยหลัง, หรือไม่เพิ่มค่า i หลังการลบ

    import java.util.ArrayList;
    
    public class Main {
        public static void main(String[] args) {
            ArrayList<Integer> nums = new ArrayList<Integer>();
            for (int n : new int[]{4, 7, 4, 9, 4}) nums.add(n);
            // Remove every 4 — loop backwards so removals don't skip items.
            for (int i = nums.size() - 1; i >= 0; i--) {
                if (nums.get(i) == 4) nums.remove(i);
            }
            System.out.println(nums);   // [7, 9]
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • ArrayList ใช้ .size(), .get(i) และ .add(...) — ไม่ใช่ [] ที่คุณใช้กับ arrays
    • การลบรายการขณะวนลูปไปข้างหน้าตามดัชนีจะข้ามรายการถัดไป (ข้อผิดพลาดของการใช้ method remove) ให้วนลูปย้อนกลับ หรือใช้ iterator
    • เก็บออบเจกต์ ไม่ใช่พรีมิทีฟ: ใช้ ArrayList<Integer>, และ Java จะแปลงค่า int อัตโนมัติ (auto-boxing)
  • 8 การเขียนคลาส
    8.1

    ฟิลด์, Constructor และเมธอด

    คลาสคือแบบจำลองสำหรับออบเจกต์ ฟิลด์เก็บข้อมูล Constructor ตั้งค่าออบเจกต์ใหม่ และเมธอดคือการทำงาน this.name หมายความว่า "name ของออบเจกต์นี้" สร้างออบเจกต์ด้วย new

    public class Main {
        public static void main(String[] args) {
            Dog d = new Dog("Rex", 3);
            System.out.println(d.describe());   // Rex is 3 years old
            d.haveBirthday();
            System.out.println(d.describe());   // Rex is 4 years old
        }
    }
    
    class Dog {
        private String name;
        private int age;
    
        public Dog(String name, int age) {   // constructor
            this.name = name;
            this.age = age;
        }
    
        public String describe() {
            return name + " is " + age + " years old";
        }
    
        public void haveBirthday() {
            age++;
        }
    }
    

    สมาชิก static เป็นของคลาสโดยตรง ไม่ใช่ของออบเจกต์ใดออบเจกต์หนึ่ง เรียกใช้ static method จากชื่อคลาส — เช่น Math.max — และ static field จะถูกแชร์โดยทุกออบเจกต์:

    public class Main {
        public static void main(String[] args) {
            System.out.println(Counter.made());   // 0
            new Counter();
            new Counter();
            System.out.println(Counter.made());   // 2
        }
    }
    
    class Counter {
        private static int count = 0;      // shared by ALL Counter objects
    
        public Counter() { count++; }
    
        public static int made() {         // called on the class: Counter.made()
            return count;
        }
    }
    
    Fields store state; constructor builds; methods act
    Fields store state; constructor builds; methods act
    8.2

    Encapsulation (การห่อหุ้มข้อมูล)

    Encapsulation ควบคุมการเข้าถึงสถานะของ object กำหนดให้ fields เป็น private เพื่อป้องกันไม่ให้คลาสอื่นเข้าถึงโดยตรง; accessor (getter) อ่านสถานะ และ mutator เปลี่ยนแปลงมัน setter เป็นประเภทหนึ่งของ mutator private ไม่ตรวจสอบค่า: constructor และ methods ที่เปลี่ยนแปลงต้องมีการตรวจสอบของตนเองหรือกำหนดเงื่อนไขเริ่มต้นที่ระบุไว้ ตัวอย่างนี้สมมติว่า start มีค่าเป็นบวกหรือศูนย์ และการเพิ่มมีผลอยู่ใน int; method deposit ของมันปฏิเสธจำนวนที่ไม่ใช่บวก

    public class Main {
        public static void main(String[] args) {
            Account a = new Account(100);
            a.deposit(50);
            a.deposit(-999);                       // rejected by the guard
            System.out.println(a.getBalance());    // 150
        }
    }
    
    class Account {
        private int balance;                       // hidden from outside
    
        public Account(int start) {
            balance = start;
        }
    
        public void deposit(int amount) {
            if (amount > 0) balance += amount;     // this guard checks the deposit amount
        }
    
        public int getBalance() {                  // accessor (getter)
            return balance;
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • Constructor มีชื่อคลาสและไม่มีการ return type (แม้แต่ void ก็ไม่มี)
    • ใช้ this.field เพื่อแยกแยะฟิลด์จาก parameter ที่มีชื่อเดียวกัน
    • ทำให้ฟิลด์ private และเข้าถึงผ่าน getter/setter methods (encapsulation)
  • 9 Inheritance & polymorphism
    9.1

    การสืบทอด

    การสืบทอด (Inheritance) ช่วยให้คลาสลูกใช้คุณสมบัติจากคลาสแม่ได้ เขียน class Cat extends Animal และ Cat จะรับฟิลด์และเมทโธดที่ถูกต้องจาก Animal สมาชิกแบบส่วนตัวไม่ถูกสืบทอด; ตัวสร้าง (constructor) ก็ไม่ถูกสืบทอดเช่นกัน ให้เรียกตัวสร้างของ parent ด้วย super(...)

    public class Main {
        public static void main(String[] args) {
            Cat c = new Cat("Milo");
            c.eat();      // Milo is eating  (inherited from Animal)
            c.speak();    // Meow            (Cat's own method)
        }
    }
    
    class Animal {
        protected String name;
        public Animal(String name) { this.name = name; }
        public void eat() { System.out.println(name + " is eating"); }
    }
    
    class Cat extends Animal {
        public Cat(String name) { super(name); }     // call Animal's constructor
        public void speak() { System.out.println("Meow"); }
    }
    
    Cat และ Dog สืบทอด Animal: พวกมันสืบทอดสมาชิกจาก Animal และเพิ่มสมาชิกของตัวเอง
    Cat และ Dog สืบทอด Animal: พวกมันสืบทอดสมาชิกจาก Animal และเพิ่มสมาชิกของตัวเอง
    9.2

    Polymorphism & toString

    subclass สามารถ override method เพื่อแทนที่เวอร์ชันของ parent Polymorphism หมายความว่าตัวแปร Shape สามารถเก็บ subtype ใดก็ได้ และ Java เลือก toString ที่ถูกต้องในขณะ run time System.out.println(obj) จะเรียก obj.toString() โดยอัตโนมัติ

    public class Main {
        public static void main(String[] args) {
            Shape[] shapes = { new Circle(2), new Square(3) };
            for (Shape s : shapes) {
                System.out.println(s);          // each calls its own toString
            }
        }
    }
    
    class Shape {
        public String toString() { return "a shape"; }
    }
    
    class Circle extends Shape {
        private int r;
        public Circle(int r) { this.r = r; }
        public String toString() { return "Circle r=" + r; }     // override
    }
    
    class Square extends Shape {
        private int side;
        public Square(int side) { this.side = side; }
        public String toString() { return "Square side=" + side; }   // override
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • Override method ต้องตรงกับ signature พอดี; เพิ่ม @Override เพื่อให้compiler จับความผิดพลาดได้
    • super(...) ต้องเป็นบรรทัดแรกของ subclass constructor
    • ออบเจกต์ subclass IS-A ออบเจกต์ superclass แต่ในทางกลับกันไม่จริง
  • 10 Recursion
    10.1

    การเรียกซ้ำ

    Recursion คือเมธอดที่เรียกตัวเอง ทุก recursion ต้องการ base case (จุดหยุด) และ recursive call ที่เข้าใกล้มัน หากไม่มี base case จะไม่หยุดและ crash ด้วย stack overflow

    Call stack สำหรับ factorial(3): ทุก call รอแล้ว return ตามลำดับย้อนกลับ
    Call stack สำหรับ factorial(3): ทุก call รอแล้ว return ตามลำดับย้อนกลับ
    public class Main {
        public static void main(String[] args) {
            System.out.println(factorial(5));   // 120
        }
    
        public static int factorial(int n) {
            if (n <= 1) return 1;            // base case
            return n * factorial(n - 1);     // recursive call: n * (n-1)!
        }
    }
    

    Trace ได้: factorial(5) รอ factorial(4), ซึ่งรอ factorial(3)… ลงไปถึง factorial(1) ที่ return ค่า 1 จากนั้นคำตอบจะคูณย้อนกลับขึ้น: 1 → 2 → 6 → 24 → 120

    Recursion ยังทำงานกับ Strings ได้ — ถอดตัวอักษรออกทีละตัวในแต่ละครั้ง:

    public class Main {
        public static void main(String[] args) {
            System.out.println(reverse("PYTHON"));   // NOHTYP
        }
    
        static String reverse(String s) {
            if (s.length() <= 1) return s;               // base case
            return reverse(s.substring(1)) + s.charAt(0);
        }
    }
    

    Merge sort เป็น sorting แบบ递归ในข้อสอบ AP: แบ่ง-array เป็นสองส่วน, sort แต่ละส่วนแบบ递归, แล้ว merge ทั้งสองส่วนที่ sorted แล้ว ทำงานได้ใน O(n log n) — เร็วกว่าการ sort แบบ O(n²) บน array ขนาดใหญ่มาก

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] a = {5, 2, 9, 1, 7, 3};
            mergeSort(a, 0, a.length - 1);
            System.out.println(Arrays.toString(a));   // [1, 2, 3, 5, 7, 9]
        }
    
        static void mergeSort(int[] a, int lo, int hi) {
            if (lo >= hi) return;                 // base case: one element
            int mid = (lo + hi) / 2;
            mergeSort(a, lo, mid);                // sort the left half
            mergeSort(a, mid + 1, hi);            // sort the right half
            merge(a, lo, mid, hi);                // merge the two halves
        }
    
        static void merge(int[] a, int lo, int mid, int hi) {
            int[] tmp = new int[hi - lo + 1];
            int i = lo, j = mid + 1, k = 0;
            while (i <= mid && j <= hi) {
                if (a[i] <= a[j]) tmp[k++] = a[i++];
                else              tmp[k++] = a[j++];
            }
            while (i <= mid) tmp[k++] = a[i++];
            while (j <= hi)  tmp[k++] = a[j++];
            for (k = 0; k < tmp.length; k++) a[lo + k] = tmp[k];
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • การเรียกซ้ำต้องการกรณีฐาน มิฉะนั้นจะเกิด StackOverflowError
    • การเรียก recursive แต่ละครั้งต้องเคลื่อนเข้าใกล้ base case มากขึ้น
    • Trace ตัวอย่างเล็กๆ ด้วยมือเพื่อตรวจสอบว่า recursion return ค่าที่ถูกต้อง
    • ใน merge sort,ขั้นตอน merge ทำงานจริง; การ recursiveแค่แบ่ง-array เท่านั้น
  • 11 Searching & sorting
    11.1

    Linear & binary search

    Linear search ตรวจสอบทุกองค์ประกอบ — ใช้งานได้กับทุก array Binary search รวดเร็วมากแต่ต้องการ sorted array: ดูค่าตรงกลาง แล้วทิ้งครึ่งหนึ่งทุกขั้นตอน ทั้งคู่ return index, หรือ -1 หากไม่พบ

    public class Main {
        public static void main(String[] args) {
            int[] a = {2, 5, 8, 12, 16, 23};      // sorted, so binary search works
            System.out.println(linear(a, 12));    // 3
            System.out.println(binary(a, 12));    // 3
            System.out.println(binary(a, 9));     // -1 (not found)
        }
    
        static int linear(int[] a, int target) {
            for (int i = 0; i < a.length; i++)
                if (a[i] == target) return i;
            return -1;
        }
    
        static int binary(int[] a, int target) {
            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;
            }
            return -1;
        }
    }
    
    Binary search แบ่งช่วงครึ่งหนึ่งทุกขั้นตอน ดังนั้น sorted array ถูกค้นหาใน O(log n)
    Binary search แบ่งช่วงครึ่งหนึ่งทุกขั้นตอน ดังนั้น sorted array ถูกค้นหาใน O(log n)
    11.2

    Selection & insertion sort

    Selection sort หาค่าที่เหลือเล็กสุดซ้ำๆ แล้วสลับไปไว้หน้า Insertion sort นำค่าแต่ละตัวมาเลื่อนกลับเข้าไปในตำแหน่งที่ถูกต้องในชุดข้อมูลที่ sorted แล้ว

    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] a = {5, 2, 9, 1, 7};
            for (int i = 0; i < a.length - 1; i++) {
                int min = i;
                for (int j = i + 1; j < a.length; j++)
                    if (a[j] < a[min]) min = j;
                int t = a[min]; a[min] = a[i]; a[i] = t;   // swap into place
            }
            System.out.println(Arrays.toString(a));   // [1, 2, 5, 7, 9]
        }
    }
    
    import java.util.Arrays;
    
    public class Main {
        public static void main(String[] args) {
            int[] a = {5, 2, 9, 1, 7};
            for (int i = 1; i < a.length; i++) {
                int key = a[i], j = i - 1;
                while (j >= 0 && a[j] > key) {    // shift bigger values right
                    a[j + 1] = a[j];
                    j--;
                }
                a[j + 1] = key;                  // drop key into the gap
            }
            System.out.println(Arrays.toString(a));   // [1, 2, 5, 7, 9]
        }
    }
    

    เปรียบเทียบความเร็วกัน:

    Algorithm Time
    linear search O(n)
    binary search O(log n), เฉพาะ sorted arrays
    selection / insertion sort O(n²)
    merge sort (topic 10) O(n log n)

    ข้อผิดพลาดที่พบบ่อย

    • Binary search ใช้งานได้เฉพาะกับ sorted array เท่านั้น
    • Linear search คือ O(n); Binary search คือ O(log n) แต่ต้องทำ sort ก่อน
    • Selection และ insertion sort คือ O(n²) — เข้าใจง่าย แต่ช้ากับข้อมูลขนาดใหญ่
  • 12 Files & the FRQ
    12.1

    ไฟล์ข้อความกับ Scanner

    Scanner อ่านข้อความบรรทัดต่อบรรทัด สำหรับไฟล์จริงคุณเขียน new Scanner(new File("scores.txt")); ที่นี่เราห่อหุ้ม String เพื่อให้ตัวอย่างรันได้ทุกที่ ใช้ .split(" ") เพื่อแบ่งบรรทัดออกเป็นส่วน และ Integer.parseInt(...) เพื่อ parse ตัวเลขจากข้อความ

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            // Real file:  Scanner in = new Scanner(new File("scores.txt"));
            String data = "Alice 80\nBob 95\nCara 72";
            Scanner in = new Scanner(data);
            int total = 0, count = 0;
            while (in.hasNextLine()) {
                String line = in.nextLine();
                String[] parts = line.split(" ");      // break the line on the space
                total += Integer.parseInt(parts[1]);
                count++;
            }
            System.out.println("average = " + (total / count));   // average = 82
        }
    }
    
    Scanner reads lines while hasNextLine is true
    Scanner reads lines while hasNextLine is true
    12.2

    ประเภทคำถาม FRQ ของ AP

    การสอบ AP CS A มีคำถามแบบตอบเอง (free-response) สี่ข้อ แต่ละข้อมีรูปแบบคงที่ดังนี้:

    • Q1 — Methods & control: เขียน methods ตามสเปกที่กำหนด; loops, if, String/Math.
    • Q2 — Class design: เขียน class ครบถ้วน (fields, constructor, methods) จากคำอธิบาย
    • Q3 — Array / ArrayList: ประมวลผล array แบบ 1-D หรือ ArrayList (search, count, สร้างลิสต์ใหม่)
    • Q4 — 2-D array: Traverse ตารางตารางโดยแถวและคอลัมน์

    ทักษะที่ใช้คือสิ่งเดิมเสมอ: อ่านสเปก, เขียน method ตามที่ระบุไว้พอดี, Return type ที่ถูกต้อง

    public class Main {
        public static void main(String[] args) {
            // Q1 style: implement a method to a spec, then it is tested.
            System.out.println(countEven(new int[]{4, 7, 10, 3, 6}));   // 3
        }
    
        /** Returns how many values in arr are even. */
        public static int countEven(int[] arr) {
            int count = 0;
            for (int x : arr)
                if (x % 2 == 0) count++;
            return count;
        }
    }
    

    ข้อผิดพลาดที่พบบ่อย

    • nextInt() จะทิ้งบรรทัดว่างไว้ข้างหลัง ดังนั้น nextLine() ถัดไปจะอ่านบรรทัดว่าง — ต้องอ่านมันออกไปก่อน
    • ตรวจสอบ hasNext() ก่อนอ่าน เพื่อหลีกเลี่ยงการอ่านเกินขอบเขตของไฟล์
    • ใน FRQ ให้ดู method header อย่างละเอียด: ตรงกับ return type และ parameters พอดี

เข้าสู่ระบบหรือสร้างบัญชี

IGCSE, A-Level & AP