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基础,为后续的深入学习打下坚实基础!

posted @ 2025-10-23 13:09  阿瓜不瓜  阅读(26)  评论(2)    收藏  举报