Java基礎全面復盤:從入門到進階的核心要點梳理
引言
Java作為一門經典的面向對象編程語言,自1995年誕生以來,始終保持著旺盛的生命力。無論你是剛剛接觸Java的初學者,還是希望鞏固基礎的開發者,進行一次全面的基礎復盤都大有裨益。本文將系統性地梳理Java核心知識點,幫助你構建完整的知識體系。
一、Java開發環境搭建
JDK安裝與配置
# 檢查Java版本 java -version javac -version # 設置環境變量(示例) JAVA_HOME=/path/to/jdk PATH=$JAVA_HOME/bin:$PATH
二、Java基礎語法
變量與數據類型
public class DataTypes { public static void main(String[] args) { // 基本數據類型 byte b = 127; // 8位 short s = 32767; // 16位 int i = 2147483647; // 32位 long l = 9223372036854775807L; // 64位 float f = 3.14f; // 32位浮點 double d = 3.1415926535; // 64位浮點 char c = 'A'; // 16位Unicode boolean bool = true; // 1位 // 引用數據類型 String str = "Hello Java"; int[] array = {1, 2, 3}; } }
運算符詳解
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 System.out.println(a % b); // 1 // 關系運算符 System.out.println(a > b); // true System.out.println(a == b); // false // 邏輯運算符 boolean x = true, y = false; System.out.println(x && y); // false System.out.println(x || y); // true System.out.println(!x); // false // 三元運算符 int max = (a > b) ? a : b; // 10 } }
流程控制結構
public class ControlFlow { public static void main(String[] args) { // if-else語句 int score = 85; if (score >= 90) { System.out.println("優秀"); } else if (score >= 80) { System.out.println("良好"); // 輸出這個 } else { System.out.println("及格"); } // 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("其他"); } // 循環結構 for (int i = 0; i < 5; i++) { System.out.println("for循環: " + i); } int j = 0; while (j < 3) { System.out.println("while循環: " + j); j++; } int k = 0; do { System.out.println("do-while循環: " + k); k++; } while (k < 3); } }
三、面向對象編程
類與對象
// 類的定義 public class Person { // 字段(屬性) private String name; private int age; // 構造方法 public Person() { this.name = "未知"; this.age = 0; } public Person(String name, int age) { this.name = name; this.age = age; } // 方法 public void introduce() { System.out.println("我叫" + name + ",今年" + age + "歲"); } // Getter和Setter public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if (age >= 0) { this.age = age; } } } // 使用類 public class OOPDemo { public static void main(String[] args) { Person person1 = new Person(); Person person2 = new Person("張三", 25); person1.introduce(); // 我叫未知,今年0歲 person2.introduce(); // 我叫張三,今年25歲 } }
三大特性:封裝、繼承、多態
// 封裝示例 public class BankAccount { private double balance; public void deposit(double amount) { if (amount > 0) { balance += amount; } } public boolean withdraw(double amount) { if (amount > 0 && balance >= amount) { balance -= amount; return true; } return false; } public double getBalance() { return balance; } } // 繼承示例 class Animal { protected String name; public Animal(String name) { this.name = name; } public void eat() { System.out.println(name + "在吃東西"); } } class Dog extends Animal { public Dog(String name) { super(name); } public void bark() { System.out.println(name + "在汪汪叫"); } // 方法重寫 @Override public void eat() { System.out.println(name + "在吃狗糧"); } } // 多態示例 public class PolymorphismDemo { public static void main(String[] args) { Animal myAnimal = new Dog("旺財"); myAnimal.eat(); // 旺財在吃狗糧 - 多態的表現 } }
抽象類與接口
// 抽象類 abstract class Shape { protected String color; public Shape(String color) { this.color = color; } // 抽象方法 public abstract double calculateArea(); // 具體方法 public void displayColor() { System.out.println("顏色: " + color); } } class Circle extends Shape { private double radius; public Circle(String color, double radius) { super(color); this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; } } // 接口 interface Flyable { void fly(); // 隱式抽象方法 default void takeOff() { // 默認方法 System.out.println("準備起飛"); } static void showFeature() { // 靜態方法 System.out.println("可以飛行"); } } interface Swimmable { void swim(); } // 實現多個接口 class Duck implements Flyable, Swimmable { @Override public void fly() { System.out.println("鴨子在飛行"); } @Override public void swim() { System.out.println("鴨子在游泳"); } }
四、異常處理
異常體系結構
public class ExceptionHandling { public static void main(String[] args) { // try-catch-finally try { int result = divide(10, 0); System.out.println("結果: " + result); } catch (ArithmeticException e) { System.out.println("捕獲算術異常: " + e.getMessage()); } catch (Exception e) { System.out.println("捕獲其他異常: " + e.getMessage()); } finally { System.out.println("finally塊總是執行"); } // 拋出異常 try { checkAge(15); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } public static int divide(int a, int b) { return a / b; } public static void checkAge(int age) { if (age < 18) { throw new IllegalArgumentException("年齡必須大于等于18歲"); } System.out.println("年齡驗證通過"); } } // 自定義異常 class InsufficientBalanceException extends Exception { public InsufficientBalanceException(String message) { super(message); } } class BankAccount { private double balance; public void withdraw(double amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("余額不足,當前余額: " + balance); } balance -= amount; } }
五、集合框架
常用集合類
import java.util.*; public class CollectionDemo { public static void main(String[] args) { // List接口 - 有序可重復 List<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Apple"); // 允許重復 List<String> linkedList = new LinkedList<>(); linkedList.add("Cat"); linkedList.add("Dog"); // Set接口 - 無序不重復 Set<String> hashSet = new HashSet<>(); hashSet.add("Red"); hashSet.add("Green"); hashSet.add("Red"); // 不會重復添加 Set<String> treeSet = new TreeSet<>(); treeSet.add("Zoo"); treeSet.add("Apple"); treeSet.add("Banana"); // 自動排序: [Apple, Banana, Zoo] // Map接口 - 鍵值對 Map<String, Integer> hashMap = new HashMap<>(); hashMap.put("Alice", 25); hashMap.put("Bob", 30); hashMap.put("Alice", 26); // 更新值 Map<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Orange", 5); treeMap.put("Apple", 3); treeMap.put("Banana", 7); // 按鍵排序: {Apple=3, Banana=7, Orange=5} // 遍歷集合 for (String fruit : arrayList) { System.out.println(fruit); } for (Map.Entry<String, Integer> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } } }
六、輸入輸出流
文件操作
import java.io.*; import java.nio.file.*; public class IODemo { public static void main(String[] args) { // 使用File類 File file = new File("test.txt"); try { // 創建文件 if (file.createNewFile()) { System.out.println("文件創建成功"); } // 寫入文件 FileWriter writer = new FileWriter(file); writer.write("Hello Java IO\n"); writer.write("這是第二行"); writer.close(); // 讀取文件 FileReader reader = new FileReader(file); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } catch (IOException e) { e.printStackTrace(); } // 使用NIO (Java 7+) try { Path path = Paths.get("test_nio.txt"); Files.write(path, Arrays.asList("第一行", "第二行", "第三行"), StandardCharsets.UTF_8); List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); for (String text : lines) { System.out.println(text); } } catch (IOException e) { e.printStackTrace(); } } }
七、多線程編程
線程創建與同步
public class ThreadDemo { public static void main(String[] args) { // 繼承Thread類 MyThread thread1 = new MyThread(); thread1.start(); // 實現Runnable接口 Thread thread2 = new Thread(new MyRunnable()); thread2.start(); // 使用Lambda表達式 Thread thread3 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Lambda線程: " + i); } }); thread3.start(); // 線程同步示例 Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("最終計數: " + counter.getCount()); } } class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("繼承Thread: " + i); } } } class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("實現Runnable: " + i); } } } // 線程安全計數器 class Counter { private int count = 0; public synchronized void increment() { count++; } public int getCount() { return count; } }
八、Java新特性
Java 8+ 重要特性
import java.util.*; import java.util.stream.*; import java.time.*; public class NewFeatures { public static void main(String[] args) { // Lambda表達式 List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); // 傳統方式 Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return a.compareTo(b); } }); // Lambda方式 Collections.sort(names, (a, b) -> a.compareTo(b)); // Stream API List<String> filteredNames = names.stream() .filter(name -> name.startsWith("A")) .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(filteredNames); // [ALICE] // 方法引用 names.forEach(System.out::println); // Optional類 - 避免空指針異常 Optional<String> optionalName = Optional.ofNullable(getName()); String result = optionalName.orElse("默認名稱"); System.out.println(result); // 新的日期時間API LocalDate today = LocalDate.now(); LocalTime now = LocalTime.now(); LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("今天: " + today); System.out.println("現在: " + now); System.out.println("當前日期時間: " + currentDateTime); // 日期計算 LocalDate nextWeek = today.plusWeeks(1); Period period = Period.between(today, nextWeek); System.out.println("下周: " + nextWeek); System.out.println("間隔: " + period.getDays() + "天"); } private static String getName() { return Math.random() > 0.5 ? "張三" : null; } }
Java的世界博大精深,基礎扎實才能在編程道路上走得更遠。希望這篇復盤文章能幫助你鞏固Java基礎,為后續的深入學習打下堅實基礎!

浙公網安備 33010602011771號