Java មេរៀនពេញលេញ · ពីដំបូងដល់ Expert

សិក្សា Java Programming ជាភាសាខ្មែរ — ចាប់ពី Hello World រហូតដល់ Advanced OOP, Collections, Generics, Threads

18+
មេរៀន
3
កម្រឹត
60+
ឧទាហរណ៍
100%
ភាសាខ្មែរ
🟢 កម្រឹតចាប់ផ្តើម — Beginner

ទិដ្ឋភាពទូទៅ Java និង Program ដំបូង

What is Java · JDK/JVM/JRE · Hello World

Java គឺជាភាសា Programming Object-Oriented ដែលបង្កើតដោយ James Gosling នៅ Sun Microsystems ឆ្នាំ ១៩៩៥។ Java ដំណើរការតាមគោលការណ៍ "Write Once, Run Anywhere" (WORA) — មានន័យថាសរសេរម្ដង ប្រើបាននៅគ្រប់ Platform។

ហេតុអ្វីត្រូវរៀន Java?

  • ភាសាដ៏ពេញនិយម ប្រើសម្រាប់ Android Apps, Web Apps, Enterprise Systems
  • Platform Independent ដំណើរការបានគ្រប់ OS
  • Security ខ្ពស់ Garbage Collection ស្វ័យប្រវត្តិ
  • Community ធំ មាន Library ច្រើន

Java Architecture: Source Code (.java) → Java Compiler (javac) → Bytecode (.class) → JVM → Output

HelloWorld.java
// Java Program ដំបូងបំផុត
public class HelloWorld {

    public static void main(String[] args) {
        // បោះពុម្ពអក្សរទៅ Console
        System.out.println("Hello, World!");
        System.out.println("សួស្តី ពិភពលោក!");
        System.out.print("ខ្ញុំកំពុងរៀន Java "); // គ្មាន newline
        System.out.println("☕");
    }
}
Hello, World!
សួស្តី ពិភពលោក!
ខ្ញុំកំពុងរៀន Java ☕
public class HelloWorld — ឈ្មោះ Class ត្រូវដូចឈ្មោះ File (.java)
public static void main(String[] args) — Entry Point គឺ Method ចម្បង
System.out.println() — print + newline | print() — print គ្មាន newline

Variables និង Data Types

Primitive Types · Reference Types · Type Casting

Java មាន Primitive Types ៨ ដែល built-in ក្នុង Language:

Typeន័យទំហំDefaultឧទាហរណ៍
byteចំនួនតូច1 byte0byte b = 100;
shortចំនួនខ្លី2 bytes0short s = 1000;
intចំនួនគត់4 bytes0int x = 42;
longចំនួនគត់ធំ8 bytes0Llong l = 100L;
floatទស្សភាគ4 bytes0.0ffloat f = 3.14f;
doubleទស្សភាគ (ច្រើន)8 bytes0.0ddouble d = 3.14;
charតួអក្សរ ១2 bytes'\u0000'char c = 'A';
booleantrue/false1 bitfalseboolean ok = true;
DataTypes.java
public class DataTypes {
    public static void main(String[] args) {

        // Primitive Types
        int     age     = 20;
        double  height  = 1.75;
        char    grade   = 'A';
        boolean student = true;
        long    pop     = 8000000000L;

        // Reference Type
        String name = "សុខ វិចិត្រ";

        // var (Java 10+) — Type Inference
        var score = 95;

        // Constants (final)
        final double PI = 3.14159265358979;

        System.out.println("ឈ្មោះ: " + name);
        System.out.println("អាយុ: " + age);
        System.out.println("ប្រជាជន: " + pop);

        // Type Casting
        double d = 9.99;
        int    i = (int) d;  // Explicit cast → 9
        System.out.println("Cast: " + i);
    }
}
ឈ្មោះ: សុខ វិចិត្រ
អាយុ: 20
ប្រជាជន: 8000000000
Cast: 9

Operators (ប្រមាណវិធី)

Arithmetic · Comparison · Logical · Bitwise · Ternary

ប្រភេទOperatorsន័យ
Arithmetic+ - * / % ++ --គណនា
Comparison== != > < >= <=ប្រៀបធៀប → boolean
Logical&& || !AND OR NOT
Assignment= += -= *= /= %=ដាក់តម្លៃ
Ternarycondition ? a : bif-else ខ្លី
Bitwise& | ^ ~ << >>ប្រតិបត្តិ Bit
Operators.java
public class Operators {
    public static void main(String[] args) {
        int a = 10, b = 3;

        System.out.println(a + b);   // 13
        System.out.println(a - b);   // 7
        System.out.println(a * b);   // 30
        System.out.println(a / b);   // 3 (Integer division)
        System.out.println(a % b);   // 1

        // Ternary Operator
        String result = (a > b) ? "a ធំជាង" : "b ធំជាង";
        System.out.println(result); // a ធំជាង

        // Compound assignment
        a += 5;   // a = a + 5 = 15
        a *= 2;   // a = 30
        System.out.println("a = " + a);

        // Logical
        boolean x = true, y = false;
        System.out.println(x && y); // false
        System.out.println(x || y); // true
        System.out.println(!x);    // false
    }
}

Input / Output

Scanner · System.out · printf · format

InputOutput.java
import java.util.Scanner;

public class InputOutput {
    public static void main(String[] args) {

        // បង្កើត Scanner Object
        Scanner sc = new Scanner(System.in);

        System.out.print("សូមបញ្ចូលឈ្មោះ: ");
        String name = sc.nextLine();    // ទទួលបន្ទាត់

        System.out.print("សូមបញ្ចូលអាយុ: ");
        int age = sc.nextInt();         // ទទួល int

        System.out.print("GPA: ");
        double gpa = sc.nextDouble();   // ទទួល double

        // println — basic
        System.out.println("ឈ្មោះ: " + name);

        // printf — formatted output
        System.out.printf("អាយុ: %d ឆ្នាំ%n", age);
        System.out.printf("GPA: %.2f%n", gpa);

        // String.format
        String msg = String.format("[%s | %d | %.1f]", name, age, gpa);
        System.out.println(msg);

        sc.close(); // បិទ Scanner
    }
}
nextLine() ទទួលអត្ថបទ | nextInt() ចំនួន int | nextDouble() ចំនួន decimal
%d=integer, %f=float, %s=string, %n=newline ក្នុង printf

Control Flow — if / else / switch

Conditional Statements · Switch Expression (Java 14+)

ControlFlow.java
public class ControlFlow {
    public static void main(String[] args) {

        int score = 85;

        // if / else if / else
        if (score >= 90) {
            System.out.println("ថ្នាក់ A ★");
        } else if (score >= 80) {
            System.out.println("ថ្នាក់ B");
        } else if (score >= 70) {
            System.out.println("ថ្នាក់ C");
        } else {
            System.out.println("ត្រូវពិនិត្យម្ដងទៀត");
        }

        // Traditional switch
        int day = 3;
        switch (day) {
            case 1: System.out.println("ចន្ទ");  break;
            case 2: System.out.println("អង្គារ"); break;
            case 3: System.out.println("ពុធ");  break;
            default: System.out.println("ថ្ងៃផ្សេង");
        }

        // Switch Expression (Java 14+) — Modern style
        String dayName = switch (day) {
            case 1 -> "ថ្ងៃចន្ទ";
            case 2 -> "ថ្ងៃអង្គារ";
            case 3 -> "ថ្ងៃពុធ";
            default -> "ថ្ងៃផ្សេង";
        };
        System.out.println(dayName);
    }
}
ថ្នាក់ B
ពុធ
ថ្ងៃពុធ

Loops (រង្វិលជុំ)

for · while · do-while · for-each · break/continue

Loops.java
public class Loops {
    public static void main(String[] args) {

        // for loop
        System.out.print("for: ");
        for (int i = 1; i <= 5; i++) {
            System.out.print(i + " ");
        }
        System.out.println();

        // while loop
        System.out.print("while: ");
        int n = 1;
        while (n <= 5) {
            System.out.print(n++ + " ");
        }
        System.out.println();

        // do-while loop (ដំណើរការ១ដងជានិច្ច)
        int x = 1;
        do {
            System.out.print(x + " ");
            x++;
        } while (x <= 3);
        System.out.println();

        // for-each (Enhanced for)
        int[] nums = {10, 20, 30, 40};
        System.out.print("each: ");
        for (int num : nums) {
            System.out.print(num + " ");
        }
        System.out.println();

        // break & continue
        for (int j = 0; j < 10; j++) {
            if (j == 3) continue; // រំលង
            if (j == 7) break;    // ចេញ
            System.out.print(j + " ");
        }
        System.out.println();
    }
}
for: 1 2 3 4 5
while: 1 2 3 4 5
1 2 3
each: 10 20 30 40
0 1 2 4 5 6
🟡 កម្រឹតមធ្យម — Intermediate

Methods (វិធីសាស្ត្រ)

Method Declaration · Overloading · Recursion

Methods.java
public class Methods {

    // Method ដែល return តម្លៃ
    static int add(int a, int b) {
        return a + b;
    }

    // void Method (មិន return)
    static void greet(String name) {
        System.out.println("សួស្តី, " + name + "!");
    }

    // Method Overloading
    static double area(double r)           { return Math.PI * r * r; }
    static double area(double w, double h) { return w * h; }

    // Recursion — Factorial
    static long factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }

    // Varargs — Parameters ចំនួនអថេរ
    static int sum(int... numbers) {
        int total = 0;
        for (int n : numbers) total += n;
        return total;
    }

    public static void main(String[] args) {
        System.out.println(add(5, 8));         // 13
        greet("វណ្ណា");
        System.out.printf("ក្រូ: %.2f%n", area(5.0));
        System.out.printf("ចតុ: %.2f%n", area(4.0, 6.0));
        System.out.println("5! = " + factorial(5)); // 120
        System.out.println(sum(1,2,3,4,5));    // 15
    }
}
13
សួស្តី, វណ្ណា!
ក្រូ: 78.54
ចតុ: 24.00
5! = 120
15

Arrays (អារ៉េ)

1D · 2D · Arrays class · Enhanced for

ArraysDemo.java
import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {

        // ប្រកាស Array
        int[] scores = {85, 92, 78, 95, 88};

        // ប្រវែង
        System.out.println("ចំនួន: " + scores.length);

        // Sort
        Arrays.sort(scores);
        System.out.println("Sort: " + Arrays.toString(scores));

        // Binary Search
        int idx = Arrays.binarySearch(scores, 88);
        System.out.println("88 នៅ index: " + idx);

        // Copy Array
        int[] copy = Arrays.copyOf(scores, 3);
        System.out.println("Copy(3): " + Arrays.toString(copy));

        // 2D Array (Matrix)
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        System.out.println("Matrix:");
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }

        // Calculate average
        double sum = 0;
        for (int s : scores) sum += s;
        System.out.printf("មធ្យម: %.2f%n", sum / scores.length);
    }
}

OOP — Classes និង Objects

Class Declaration · Fields · Methods · Instance

Java គឺជា Object-Oriented Language ដ៏ស្ទែង — Class គឺជា Blueprint (ប្លង់) ហើយ Object គឺជា Instance (ការបង្ហាញ) ពី Class នោះ។

Student.java
public class Student {

    // Fields (Instance Variables)
    String name;
    int    age;
    double gpa;

    // Instance Method
    void study() {
        System.out.println(name + " កំពុងរៀន...");
    }

    void showInfo() {
        System.out.printf("[%s | %d ឆ្នាំ | GPA: %.1f]%n",
                          name, age, gpa);
    }

    // Static Method — ចូលដោយ Class
    static void schoolName() {
        System.out.println("សាលា: RUPP");
    }
}

// Main Class
class Main {
    public static void main(String[] args) {

        // បង្កើត Object ពី Class
        Student s1 = new Student();
        s1.name = "វណ្ណា";
        s1.age  = 20;
        s1.gpa  = 3.8;
        s1.showInfo();
        s1.study();

        Student s2 = new Student();
        s2.name = "សុភា";
        s2.age  = 22;
        s2.gpa  = 3.5;
        s2.showInfo();

        Student.schoolName(); // Static call
    }
}
[វណ្ណា | 20 ឆ្នាំ | GPA: 3.8]
វណ្ណា កំពុងរៀន...
[សុភា | 22 ឆ្នាំ | GPA: 3.5]
សាលា: RUPP
១០

Constructors

Default · Parameterized · Constructor Overloading · this keyword

Car.java
public class Car {
    String brand;
    String color;
    int    year;

    // Default Constructor
    Car() {
        brand = "Unknown";
        color = "White";
        year  = 2024;
    }

    // Parameterized Constructor
    Car(String brand, String color, int year) {
        this.brand = brand; // this = Object បច្ចុប្បន្ន
        this.color = color;
        this.year  = year;
    }

    // Constructor Overloading (2 parameters)
    Car(String brand, int year) {
        this(brand, "Black", year); // ហៅ Constructor ខាងលើ
    }

    void display() {
        System.out.printf("%s [%s] (%d)%n", brand, color, year);
    }

    public static void main(String[] args) {
        Car c1 = new Car();
        Car c2 = new Car("Toyota", "Silver", 2022);
        Car c3 = new Car("Honda", 2023);

        c1.display();
        c2.display();
        c3.display();
    }
}
Unknown [White] (2024)
Toyota [Silver] (2022)
Honda [Black] (2023)
១១

Encapsulation (ការបិទសីមាព័ត៌មាន)

private · Getters/Setters · Data Validation

Encapsulation មានន័យថា លាក់ Data (private) ហើយអនុញ្ញាតឱ្យចូលដំណើរការបានតែតាម Getters/Setters

BankAccount.java
public class BankAccount {
    private String owner;
    private double balance;

    public BankAccount(String owner, double initial) {
        this.owner   = owner;
        this.balance = initial;
    }

    // Getter
    public String getOwner()  { return owner; }
    public double getBalance() { return balance; }

    // Methods with validation
    public void deposit(double amount) {
        if (amount <= 0) {
            System.out.println("❌ ចំនួនទឹកប្រាក់មិនត្រឹមត្រូវ!");
            return;
        }
        balance += amount;
        System.out.printf("✅ ដាក់ $%.2f | សមតុល្យ: $%.2f%n", amount, balance);
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            System.out.println("❌ ប្រាក់មិនគ្រប់!");
            return;
        }
        balance -= amount;
        System.out.printf("💸 ដក $%.2f | សមតុល្យ: $%.2f%n", amount, balance);
    }

    public static void main(String[] args) {
        BankAccount acc = new BankAccount("វណ្ណា", 500.0);
        acc.deposit(300);
        acc.withdraw(100);
        acc.withdraw(900);
    }
}
✅ ដាក់ $300.00 | សមតុល្យ: $800.00
💸 ដក $100.00 | សមតុល្យ: $700.00
❌ ប្រាក់មិនគ្រប់!
១២

String Methods

String Manipulation · StringBuilder · String.format

StringMethods.java
public class StringMethods {
    public static void main(String[] args) {

        String s = "  Hello Java World!  ";

        System.out.println(s.trim());             // ដកដកឃ្លាចុងចំហ
        System.out.println(s.length());           // ប្រវែង
        System.out.println(s.toUpperCase());      // ធំទាំងអស់
        System.out.println(s.toLowerCase());      // តូចទាំងអស់
        System.out.println(s.contains("Java"));  // true
        System.out.println(s.replace("Java","☕")); // ជំនួស
        System.out.println(s.trim().split(" ").length); // ចែក
        System.out.println(s.substring(8, 12));   // Jav
        System.out.println(s.charAt(8));          // H
        System.out.println(s.indexOf("Java"));   // 8
        System.out.println("Hello".equals("hello"));  // false
        System.out.println("Hello".equalsIgnoreCase("hello")); // true

        // StringBuilder — efficient string building
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 5; i++) {
            sb.append(i).append(" ");
        }
        System.out.println(sb.toString().trim());
    }
}
Hello Java World!
22
HELLO JAVA WORLD!
hello java world!
true
Hello ☕ World!
3
Java
H
8
false
true
1 2 3 4 5
🔴 កម្រឹតខ្ពស់ — Advanced
១៣

Inheritance (ការទទួលមរតក)

extends · super · Method Overriding · @Override

Inheritance.java
// Base Class (Parent)
class Animal {
    protected String name;
    protected int age;

    Animal(String name, int age) {
        this.name = name;
        this.age  = age;
    }

    void eat() { System.out.println(name + " កំពុងញ៉ាំ..."); }
    void speak() { System.out.println(name + ": ..."); }
}

// Derived Class — Dog inherits Animal
class Dog extends Animal {
    String breed;

    Dog(String name, int age, String breed) {
        super(name, age); // ហៅ Parent Constructor
        this.breed = breed;
    }

    @Override
    void speak() {
        System.out.println(name + ": វូហ្វវូ! 🐕");
    }

    void fetch() { System.out.println(name + " ចាប់បាល់!"); }
}

class Cat extends Animal {
    Cat(String name, int age) { super(name, age); }

    @Override
    void speak() {
        System.out.println(name + ": ម្យាវវ! 🐈");
    }
}

public class Inheritance {
    public static void main(String[] args) {
        Dog dog = new Dog("បូ", 3, "Golden");
        Cat cat = new Cat("មៀវ", 2);

        dog.eat();   // ទទួលមកពី Animal
        dog.speak(); // Override
        dog.fetch(); // Dog ផ្ទាល់
        cat.speak();

        // instanceof check
        System.out.println(dog instanceof Animal); // true
    }
}
បូ កំពុងញ៉ាំ...
បូ: វូហ្វវូ! 🐕
បូ ចាប់បាល់!
មៀវ: ម្យាវវ! 🐈
true
១៤

Polymorphism (ពហុរូបភាព)

Compile-time · Runtime · Abstract Classes

Polymorphism.java
// Abstract Class — មិនអាច new ដោយផ្ទាល់
abstract class Shape {
    String color;

    Shape(String color) { this.color = color; }

    // Abstract method — Subclass ត្រូវ implement
    abstract double area();
    abstract double perimeter();

    void describe() {
        System.out.printf("%s [%s] → Area: %.2f | Peri: %.2f%n",
            this.getClass().getSimpleName(), color,
            area(), perimeter());
    }
}

class Circle extends Shape {
    double radius;
    Circle(String c, double r) { super(c); radius = r; }

    @Override double area()      { return Math.PI * radius * radius; }
    @Override double perimeter() { return 2 * Math.PI * radius; }
}

class Rectangle extends Shape {
    double w, h;
    Rectangle(String c, double w, double h) {
        super(c); this.w = w; this.h = h;
    }
    @Override double area()      { return w * h; }
    @Override double perimeter() { return 2 * (w + h); }
}

public class Polymorphism {
    public static void main(String[] args) {
        Shape[] shapes = {
            new Circle("Red", 5),
            new Rectangle("Blue", 4, 6),
            new Circle("Green", 3)
        };
        for (Shape s : shapes) s.describe(); // Polymorphism!
    }
}
Circle [Red] → Area: 78.54 | Peri: 31.42
Rectangle [Blue] → Area: 24.00 | Peri: 20.00
Circle [Green] → Area: 28.27 | Peri: 18.85
១៥

Interfaces

interface · implements · Default Methods · Multiple Interfaces

Interfaces.java
// Interface — Contract ដែល Class ត្រូវ implement
interface Flyable {
    void fly();   // abstract method (implicit)
    default void land() {
        System.out.println("ចុះចត...");
    }
}

interface Swimmable {
    void swim();
}

// Class ដែល implement ច្រើន Interfaces
class Duck implements Flyable, Swimmable {
    String name;
    Duck(String name) { this.name = name; }

    @Override
    public void fly()  { System.out.println(name + ": ហើរ 🦆"); }

    @Override
    public void swim() { System.out.println(name + ": ហែល 🌊"); }
}

class Airplane implements Flyable {
    @Override
    public void fly()  { System.out.println("យន្តហោះ: ហើរ ✈️"); }
}

public class Interfaces {
    public static void main(String[] args) {
        Duck duck = new Duck("ទាតូ");
        duck.fly();
        duck.swim();
        duck.land(); // Default method

        Flyable plane = new Airplane();
        plane.fly();
        plane.land();
    }
}
ទាតូ: ហើរ 🦆
ទាតូ: ហែល 🌊
ចុះចត...
យន្តហោះ: ហើរ ✈️
ចុះចត...
១៦

Collections Framework

ArrayList · LinkedList · HashMap · HashSet · TreeMap

Collections.java
import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {

        // ===== ArrayList — Dynamic Array =====
        ArrayList<String> names = new ArrayList<>();
        names.add("វណ្ណា"); names.add("សុភា"); names.add("ដារ៉ា");
        names.add(1, "ចន្ទារ"); // បញ្ចូល index 1
        names.remove("សុភា");
        Collections.sort(names);
        System.out.println("List: " + names);

        // ===== HashMap — Key-Value =====
        HashMap<String, Integer> scores = new HashMap<>();
        scores.put("វណ្ណា", 95);
        scores.put("ដារ៉ា", 88);
        scores.put("ចន្ទារ", 92);

        System.out.println("វណ្ណា: " + scores.get("វណ្ណា"));
        System.out.println("Keys: " + scores.keySet());

        // iterate HashMap
        for (Map.Entry<String, Integer> e : scores.entrySet()) {
            System.out.printf("  %s → %d%n", e.getKey(), e.getValue());
        }

        // ===== HashSet — No Duplicates =====
        HashSet<Integer> set = new HashSet<>();
        set.add(1); set.add(2); set.add(2); set.add(3);
        System.out.println("Set: " + set); // [1, 2, 3]

        // ===== Collections Utility =====
        List<Integer> nums = Arrays.asList(5,3,8,1,9);
        System.out.println("Max: " + Collections.max(nums));
        System.out.println("Min: " + Collections.min(nums));
    }
}
១៧

Generics

Generic Classes · Methods · Bounded Types · Wildcards

Generics.java
public class Generics {

    // Generic Class — ប្រើ Type ណាក៏បាន
    static class Box<T> {
        private T value;
        Box(T v) { value = v; }
        T get()  { return value; }
        void show() {
            System.out.printf("Box<%s>: %s%n",
                value.getClass().getSimpleName(), value);
        }
    }

    // Generic Method
    static <T extends Comparable<T>> T maxOf(T a, T b) {
        return a.compareTo(b) > 0 ? a : b;
    }

    // Generic Pair
    static class Pair<A, B> {
        A first; B second;
        Pair(A a, B b) { first = a; second = b; }
        void show() {
            System.out.printf("(%s, %s)%n", first, second);
        }
    }

    public static void main(String[] args) {
        Box<Integer> intBox = new Box<>(42);
        Box<String>  strBox = new Box<>("Java");
        intBox.show();
        strBox.show();

        System.out.println(maxOf(10, 25));
        System.out.println(maxOf("Apple", "Mango"));

        Pair<String, Integer> p = new Pair<>("វណ្ណា", 95);
        p.show();
    }
}
Box<Integer>: 42
Box<String>: Java
25
Mango
(វណ្ណា, 95)
១៨

Exception Handling

try-catch-finally · throw · Custom Exceptions · Multi-catch

Exceptions.java
// Custom Exception
class InsufficientFundsException extends Exception {
    double amount;
    InsufficientFundsException(double a) {
        super("ប្រាក់ $" + a + " មិនគ្រប់!");
        amount = a;
    }
}

public class Exceptions {

    static void withdraw(double balance, double amount)
            throws InsufficientFundsException {
        if (amount > balance)
            throw new InsufficientFundsException(amount);
        System.out.printf("✅ ដក $%.2f | នៅ: $%.2f%n", amount, balance-amount);
    }

    public static void main(String[] args) {

        // Basic try-catch-finally
        try {
            int[] arr = {1, 2, 3};
            System.out.println(arr[5]); // ArrayIndexOutOfBounds
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("❌ Array: " + e.getMessage());
        } finally {
            System.out.println("🔁 Finally ដំណើរការជានិច្ច");
        }

        // Multi-catch (Java 7+)
        try {
            String s = null;
            s.length(); // NullPointerException
        } catch (NullPointerException | NumberFormatException e) {
            System.out.println("❌ Null/Number: " + e.getClass().getSimpleName());
        }

        // Custom Exception
        try {
            withdraw(500, 200);
            withdraw(500, 800); // Error!
        } catch (InsufficientFundsException e) {
            System.out.println("❌ " + e.getMessage());
        }

        System.out.println("Program នៅតែដំណើរការ ✓");
    }
}
❌ Array: Index 5 out of bounds for length 3
🔁 Finally ដំណើរការជានិច្ច
❌ Null/Number: NullPointerException
✅ ដក $200.00 | នៅ: $300.00
❌ ប្រាក់ $800.0 មិនគ្រប់!
Program នៅតែដំណើរការ ✓
១៩

File I/O

FileWriter · FileReader · BufferedReader · try-with-resources

FileIO.java
import java.io.*;
import java.nio.file.*;
import java.util.*;

public class FileIO {
    public static void main(String[] args) {

        String filename = "students.txt";

        // ===== Write File =====
        try (BufferedWriter bw = new BufferedWriter(
                new FileWriter(filename))) {
            bw.write("វណ្ណា,20,3.8\n");
            bw.write("សុភា,22,3.5\n");
            bw.write("ដារ៉ា,21,3.9\n");
            System.out.println("✅ សរសេរ File ជោគជ័យ!");
        } catch (IOException e) {
            e.printStackTrace();
        }

        // ===== Read File =====
        System.out.println("=== មាតិកា ===");
        try (BufferedReader br = new BufferedReader(
                new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = line.split(",");
                System.out.printf("ឈ្មោះ: %-8s អាយុ: %s GPA: %s%n",
                    parts[0], parts[1], parts[2]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        // ===== NIO — Modern approach (Java 7+) =====
        try {
            List<String> lines = Files.readAllLines(Path.of(filename));
            System.out.println("ចំនួនបន្ទាត់: " + lines.size());
        } catch (IOException e) { e.printStackTrace(); }
    }
}
try-with-resources — ប្រើ try (Resource r = ...) ដើម្បី Auto Close Resources ដោយស្វ័យប្រវត្តិ — គ្មានបញ្ហា Memory Leak!
២០

Multithreading

Thread · Runnable · synchronized · ExecutorService

Multithreading អនុញ្ញាតឱ្យ Program ដំណើរការ Tasks ច្រើនជាមួយគ្នា (Concurrently)។

Multithreading.java
import java.util.concurrent.*;

// Method 1: Extend Thread
class Worker extends Thread {
    String task;
    Worker(String task) { this.task = task; }

    @Override
    public void run() {
        for (int i = 1; i <= 3; i++) {
            System.out.printf("%s: ជំហាន %d%n", task, i);
            try { Thread.sleep(200); }
            catch (InterruptedException e) { }
        }
    }
}

public class Multithreading {

    // Thread-safe counter with synchronized
    static int counter = 0;
    static synchronized void increment() { counter++; }

    public static void main(String[] args) throws InterruptedException {

        // Method 1: Thread class
        Worker t1 = new Worker("Task A");
        Worker t2 = new Worker("Task B");
        t1.start(); t2.start();
        t1.join();  t2.join(); // រង់ចាំ Threads

        // Method 2: Runnable + Lambda (Modern)
        Runnable r = () -> {
            for (int i = 0; i < 1000; i++) increment();
        };
        Thread th1 = new Thread(r);
        Thread th2 = new Thread(r);
        th1.start(); th2.start();
        th1.join();  th2.join();
        System.out.println("Counter: " + counter); // 2000

        // Method 3: ExecutorService (Thread Pool)
        ExecutorService pool = Executors.newFixedThreadPool(3);
        for (int i = 1; i <= 5; i++) {
            final int id = i;
            pool.submit(() ->
                System.out.println("Task #"+id+" by "+Thread.currentThread().getName())
            );
        }
        pool.shutdown(); // ឈប់ទទួល Task ថ្មី
    }
}
⚠️
ពេល Threads ច្រើនចែករំលែក Data ដូចគ្នា ត្រូវប្រើ synchronizedatomic variables ដើម្បីការពារ Race Condition!