Cơ Bản
Hello World
public class Main { public static void main(String[] args) { System.out.println("Hello, World!"); } }
Biên Dịch & Chạy
javac Main.java # compile java Main # run java Main.java # single-file (Java 11+)
Quy Tắc Đặt Tên
ClassNamePascalCase cho class và interface
methodNamecamelCase cho method và biến
CONSTANT_NAMEUPPER_SNAKE cho hằng số
com.example.pkgTên miền ngược viết thường cho package
Kiểu Dữ Liệu
Kiểu Nguyên Thủy
byte8-bit có dấu (-128 đến 127)
short16-bit có dấu
int32-bit có dấu (số nguyên mặc định)
long64-bit có dấu (hậu tố L)
float32-bit IEEE-754 (hậu tố f)
double64-bit IEEE-754 (thập phân mặc định)
booleantrue / false
charKý tự Unicode 16-bit
Strings
String s = "hello"; String joined = s + " world"; // concatenation int len = s.length(); String sub = s.substring(0, 3); // "hel" boolean eq = s.equals("hello"); // content equality
Ép Kiểu
int i = (int) 3.14; // narrowing cast double d = i; // widening (auto) int n = Integer.parseInt("42"); // string to int String s = String.valueOf(42); // int to string
Mảng
int[] nums = {1, 2, 3}; String[] names = new String[5]; int[][] matrix = new int[3][4]; Arrays.sort(nums);
Luồng Điều Khiển
If / Else
if (x > 0) { System.out.println("positive"); } else if (x == 0) { System.out.println("zero"); } else { System.out.println("negative"); }
Switch
// Traditional switch (day) { case "Mon": doWork(); break; case "Sat": case "Sun": rest(); break; default: routine(); } // Switch expression (Java 14+) String type = switch (day) { case "Sat", "Sun" -> "weekend"; default -> "weekday"; };
Vòng Lặp
for (int i = 0; i < 10; i++) { } for (String s : list) { } // enhanced for while (condition) { } do { } while (condition);
Methods
Định Nghĩa
public static int add(int a, int b) { return a + b; }
Varargs & Nạp Chồng
static int sum(int... nums) { int total = 0; for (int n : nums) total += n; return total; } // sum(1, 2) sum(1, 2, 3) both work
Access Modifiers
publicTruy cập từ bất kỳ đâu
protectedCùng package + subclass
(default)Chỉ cùng package (không có từ khóa)
privateChỉ cùng class
Classes & Objects
Định Nghĩa Class
public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } }
Records (Java 16+)
public record Point(double x, double y) { // auto: constructor, getters, equals, hashCode, toString public double distance() { return Math.sqrt(x * x + y * y); } }
Static & Final
staticThuộc về class, không phải instance
final fieldKhông thể gán lại sau khi khởi tạo
final methodKhông thể override
final classKhông thể kế thừa
Kế Thừa
Extends
public class Animal { public void speak() { System.out.println("..."); } } public class Dog extends Animal { @Override public void speak() { System.out.println("Woof!"); } }
Abstract Classes
public abstract class Shape { abstract double area(); public void describe() { System.out.println("Area: " + area()); } }
Khái Niệm Chính
superGọi constructor hoặc method cha
@OverrideKiểm tra override lúc biên dịch
instanceofKiểm tra kiểu lúc chạy
sealed (17+)Hạn chế class nào có thể extend
Interfaces
Định Nghĩa
public interface Printable { void print(); // abstract default String format() { // default method return toString(); } static Printable of(String s) { // static method return () -> System.out.println(s); } }
Triển Khai
public class Report implements Printable, Serializable { @Override public void print() { System.out.println("Report"); } }
Functional Interfaces
Runnable() -> void
Supplier<T>() -> T
Consumer<T>T -> void
Function<T,R>T -> R
Predicate<T>T -> boolean
Comparator<T>(T, T) -> int
Collections
List
List list = new ArrayList<>(); list.add("a"); list.get(0); // "a" list.size(); // 1 List immutable = List.of("a", "b", "c");
Map
Map map = new HashMap<>(); map.put("key", 42); map.getOrDefault("key", 0); // 42 map.containsKey("key"); // true map.forEach((k, v) -> { });
Set
Set set = new HashSet<>(); set.add("a"); set.contains("a"); // true Set immutable = Set.of("a", "b", "c");
Triển Khai Phổ Biến
ArrayListMảng có thể mở rộng, truy cập ngẫu nhiên nhanh
LinkedListDanh sách liên kết đôi, chèn/xóa nhanh
HashMapBảng hash, get/put O(1)
TreeMapSắp xếp theo key, O(log n)
HashSetPhần tử duy nhất, lookup O(1)
LinkedHashMapHashMap theo thứ tự chèn
Xử Lý Exception
Try / Catch / Finally
try { int result = 10 / 0; } catch (ArithmeticException e) { System.err.println(e.getMessage()); } finally { // always executes }
Try-with-Resources
try (var reader = new BufferedReader(new FileReader(path))) { String line = reader.readLine(); } // auto-closes reader
Phân Cấp Exception
ThrowableGốc của tất cả error và exception
ErrorVấn đề nghiêm trọng (OutOfMemoryError)
ExceptionException đã kiểm tra (phải xử lý)
RuntimeExceptionChưa kiểm tra (NullPointer, IndexOutOfBounds)
Exception Tùy Chỉnh
public class AppException extends Exception { public AppException(String msg) { super(msg); } public AppException(String msg, Throwable cause) { super(msg, cause); } }
Streams & Lambdas
Cú Pháp Lambda
Comparator byLen = (a, b) -> a.length() - b.length(); Runnable task = () -> System.out.println("run"); Function len = String::length; // method ref
Stream Pipeline
List result = names.stream() .filter(n -> n.length() > 3) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());
Thao Tác Stream Phổ Biến
.filter(pred)Giữ phần tử khớp predicate
.map(func)Biến đổi từng phần tử
.flatMap(func)Map và làm phẳng stream lồng nhau
.sorted()Sắp xếp (tự nhiên hoặc với Comparator)
.distinct()Xóa trùng lặp
.limit(n)Lấy n phần tử đầu tiên
.collect()Terminal: gom vào collection
.forEach()Terminal: thực hiện hành động trên từng phần tử
.reduce()Terminal: kết hợp thành một giá trị
.count()Terminal: đếm phần tử
Generics
Generic Class & Method
public class Box { private T value; public Box(T value) { this.value = value; } public T get() { return value; } } public static List listOf(T... items) { return List.of(items); }
Kiểu Ràng Buộc & Wildcard
<T extends Number>T phải là Number hoặc subclass
<T extends A & B>Nhiều ràng buộc (class + interface)
<?>Kiểu không xác định (chỉ đọc)
<? extends T>Wildcard cận trên (producer)
<? super T>Wildcard cận dưới (consumer)
Optional & Java Hiện Đại
Optional
Optional opt = Optional.ofNullable(getValue()); String result = opt.orElse("default"); opt.ifPresent(v -> System.out.println(v)); String upper = opt.map(String::toUpperCase).orElse("");
Text Blocks (Java 15+)
String json = """ { "name": "Alice", "age": 30 } """;
Tiện Ích Hữu Ích
var (10+)Suy luận kiểu biến cục bộ
record (16+)Class mang dữ liệu bất biến
sealed (17+)Phân cấp class bị hạn chế
pattern matching (21+)instanceof với auto-cast
virtual threads (21+)Luồng nhẹ qua Thread.ofVirtual()