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
// 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("☕"); } }
សួស្តី ពិភពលោក!
ខ្ញុំកំពុងរៀន Java ☕
public static void main(String[] args) — Entry Point គឺ Method ចម្បង
System.out.println() — print + newline | print() — print គ្មាន newline
Java មាន Primitive Types ៨ ដែល built-in ក្នុង Language:
| Type | ន័យ | ទំហំ | Default | ឧទាហរណ៍ |
|---|---|---|---|---|
byte | ចំនួនតូច | 1 byte | 0 | byte b = 100; |
short | ចំនួនខ្លី | 2 bytes | 0 | short s = 1000; |
int | ចំនួនគត់ | 4 bytes | 0 | int x = 42; |
long | ចំនួនគត់ធំ | 8 bytes | 0L | long l = 100L; |
float | ទស្សភាគ | 4 bytes | 0.0f | float f = 3.14f; |
double | ទស្សភាគ (ច្រើន) | 8 bytes | 0.0d | double d = 3.14; |
char | តួអក្សរ ១ | 2 bytes | '\u0000' | char c = 'A'; |
boolean | true/false | 1 bit | false | boolean ok = true; |
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 | == != > < >= <= | ប្រៀបធៀប → boolean |
| Logical | && || ! | AND OR NOT |
| Assignment | = += -= *= /= %= | ដាក់តម្លៃ |
| Ternary | condition ? a : b | if-else ខ្លី |
| Bitwise | & | ^ ~ << >> | ប្រតិបត្តិ Bit |
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 } }
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 } }
%d=integer, %f=float, %s=string, %n=newline ក្នុង printf
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); } }
ពុធ
ថ្ងៃពុធ
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(); } }
while: 1 2 3 4 5
1 2 3
each: 10 20 30 40
0 1 2 4 5 6
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 } }
សួស្តី, វណ្ណា!
ក្រូ: 78.54
ចតុ: 24.00
5! = 120
15
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); } }
Java គឺជា Object-Oriented Language ដ៏ស្ទែង — Class គឺជា Blueprint (ប្លង់) ហើយ Object គឺជា Instance (ការបង្ហាញ) ពី Class នោះ។
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 } }
វណ្ណា កំពុងរៀន...
[សុភា | 22 ឆ្នាំ | GPA: 3.5]
សាលា: RUPP
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(); } }
Toyota [Silver] (2022)
Honda [Black] (2023)
Encapsulation មានន័យថា លាក់ Data (private) ហើយអនុញ្ញាតឱ្យចូលដំណើរការបានតែតាម Getters/Setters។
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); } }
💸 ដក $100.00 | សមតុល្យ: $700.00
❌ ប្រាក់មិនគ្រប់!
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()); } }
22
HELLO JAVA WORLD!
hello java world!
true
Hello ☕ World!
3
Java
H
8
false
true
1 2 3 4 5
// 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
// 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! } }
Rectangle [Blue] → Area: 24.00 | Peri: 20.00
Circle [Green] → Area: 28.27 | Peri: 18.85
// 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(); } }
ទាតូ: ហែល 🌊
ចុះចត...
យន្តហោះ: ហើរ ✈️
ចុះចត...
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)); } }
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<String>: Java
25
Mango
(វណ្ណា, 95)
// 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 នៅតែដំណើរការ ✓"); } }
🔁 Finally ដំណើរការជានិច្ច
❌ Null/Number: NullPointerException
✅ ដក $200.00 | នៅ: $300.00
❌ ប្រាក់ $800.0 មិនគ្រប់!
Program នៅតែដំណើរការ ✓
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 (Resource r = ...) ដើម្បី Auto Close Resources ដោយស្វ័យប្រវត្តិ — គ្មានបញ្ហា Memory Leak!Multithreading អនុញ្ញាតឱ្យ Program ដំណើរការ Tasks ច្រើនជាមួយគ្នា (Concurrently)។
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 ថ្មី } }