全面 Java 学习笔记

这份笔记为已经熟悉 Python 的计算机学生设计,旨在帮助你全面掌握 Java 语言及其在软件开发中的应用。内容从基础到进阶,包含详细注释的代码示例,逻辑清晰,适合系统学习和实践。

1. Java 基础语法

1.1 基本介绍

  • Java 是一种静态类型面向对象的编程语言,通过 JVM(Java 虚拟机)实现跨平台运行。
  • 程序入口点是 public static void main(String[] args) 方法,必须定义在类中。
  • 示例代码:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    /**
    * 基础语法示例:Hello World 程序
    */
    public class HelloWorld {
    // 程序入口点,JVM 从这里开始执行
    public static void main(String[] args) {
    // 打印欢迎信息到控制台
    System.out.println("Welcome to Java!");
    }
    }

1.2 数据类型

  • 基本类型
    • 整数:byte (8位), short (16位), int (32位), long (64位)
    • 浮点:float (32位), double (64位)
    • 字符:char (16位 Unicode)
    • 布尔:boolean (true/false)
  • 引用类型:对象、数组、字符串等。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    /**
    * 数据类型示例:展示基本类型和引用类型的声明与初始化
    */
    public class DataTypes {
    public static void main(String[] args) {
    // 声明并初始化基本数据类型
    int number = 100; // 32位整数
    double price = 19.99; // 64位浮点数
    char letter = 'A'; // 16位 Unicode 字符
    boolean isActive = true; // 布尔值

    // 声明引用类型 - 字符串
    String text = "Learning Java";

    // 打印变量值
    System.out.println("Number: " + number);
    System.out.println("Price: " + price);
    System.out.println("Letter: " + letter);
    System.out.println("Active: " + isActive);
    System.out.println("Text: " + text);
    }
    }

1.3 运算符

  • 算术+, -, *, /, %
  • 比较==, !=, <, >, <=, >=
  • 逻辑&&, ||, !
  • 位运算&, |, ^, ~, <<, >>, >>>
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    /**
    * 运算符示例:展示算术、比较和逻辑运算
    */
    public class Operators {
    public static void main(String[] args) {
    // 算术运算
    int a = 10;
    int b = 3;
    int sum = a + b; // 加法
    int mod = a % b; // 取模

    // 比较运算
    boolean isEqual = (a == b); // 判断是否相等
    boolean isGreater = (a > b); // 判断是否大于

    // 逻辑运算
    boolean result = isGreater && !isEqual; // 与操作和非操作

    // 打印结果
    System.out.println("Sum: " + sum); // 输出 13
    System.out.println("Mod: " + mod); // 输出 1
    System.out.println("Equal: " + isEqual); // 输出 false
    System.out.println("Result: " + result); // 输出 true
    }
    }

1.4 控制流

  • 条件语句if, else if, else
  • 循环for, while, do-while
  • 分支switch
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /**
    * 控制流示例:展示条件语句和循环
    */
    public class ControlFlow {
    public static void main(String[] args) {
    // 条件语句:检查数字大小
    int number = 75;
    if (number > 50) {
    System.out.println("Number is greater than 50");
    } else if (number > 0) {
    System.out.println("Number is positive but 50 or less");
    } else {
    System.out.println("Number is zero or negative");
    }

    // for 循环:打印 0 到 2
    for (int i = 0; i < 3; i++) {
    System.out.println("Loop iteration: " + i);
    }

    // switch 语句:根据值选择
    int day = 2;
    switch (day) {
    case 1:
    System.out.println("Monday");
    break;
    case 2:
    System.out.println("Tuesday");
    break;
    default:
    System.out.println("Other day");
    }
    }
    }

1.5 数组与字符串

  • 数组:固定大小,声明如 int[] arr = new int[5]; 或初始化如 int[] arr = {1, 2, 3};
  • 字符串:不可妻,常用方法包括 length(), substring(), split()
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    /**
    * 数组与字符串示例:展示数组和字符串操作
    */
    public class ArraysAndStrings {
    public static void main(String[] args) {
    // 声明并初始化数组
    int[] numbers = new int[3]; // 创建长度为 3 的数组
    numbers[0] = 1; // 设置第一个元素
    numbers[1] = 2; // 设置第二个元素
    numbers[2] = 3; // 设置第三个元素

    // 打印数组内容
    System.out.println("Array: " + java.util.Arrays.toString(numbers));

    // 声明并操作字符串
    String greeting = "Hello";
    greeting = greeting + " Java!"; // 字符串拼接
    System.out.println("Greeting: " + greeting); // 输出 "Hello Java!"

    // 字符串方法示例
    System.out.println("Length: " + greeting.length()); // 输出字符串长度
    System.out.println("Substring: " + greeting.substring(0, 5)); // 输出 "Hello"
    }
    }

2. 面向对象编程(OOP)

2.1 类与对象

  • 类是对象的模板,包含属性和方法。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    /**
    * 类与对象示例:定义 Person 类并创建对象
    */
    public class Person {
    // 成员变量:使用 private 实现封装
    private String name;
    private int age;

    // 构造方法:初始化对象属性
    public Person(String name, int age) {
    this.name = name; // this 区分成员变量和参数
    this.age = age;
    }

    // 成员方法:输出问候语
    public void sayHello() {
    System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }

    // Getter 方法:提供对私有变量的访问
    public String getName() {
    return name;
    }

    // 主方法:测试类
    public static void main(String[] args) {
    // 创建 Person 对象
    Person person = new Person("Alice", 25);
    // 调用方法
    person.sayHello(); // 输出 "Hello, my name is Alice and I am 25 years old."
    }
    }

2.2 封装、继承、多态

  • 封装:通过 privatepublic 控制访问。
  • 继承:使用 extends 关键字。
  • 多态:通过方法重写(@Override)和重载实现。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    /**
    * 继承与多态示例:Student 类继承 Person 类
    */
    public class Student extends Person {
    // 额外的成员变量
    private String studentId;

    // 构造方法:调用父类构造方法并初始化子类属性
    public Student(String name, int age, String studentId) {
    super(name, age); // 调用父类构造方法
    this.studentId = studentId;
    }

    // 重写父类方法:自定义问候语
    @Override
    public void sayHello() {
    System.out.println("Hi, I am a student named " + getName() + " with ID " + studentId);
    }

    // 主方法:测试继承和多态
    public static void main(String[] args) {
    // 创建 Student 对象
    Student student = new Student("Bob", 20, "S123");
    // 调用重写的方法
    student.sayHello(); // 输出 "Hi, I am a student named Bob with ID S123"
    }
    }

2.3 接口与抽象类

  • 抽象类:不能实例化,包含抽象方法。
  • 接口:定义行为规范,类通过 implements 实现。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    /**
    * 接口与抽象类示例:定义 Shape 抽象类和 Printable 接口
    */
    abstract class Shape {
    // 抽象方法:子类必须实现
    abstract double area();
    }

    interface Printable {
    // 接口方法:实现类必须提供
    void print();
    }

    class Circle extends Shape implements Printable {
    private double radius;

    // 构造方法
    public Circle(double radius) {
    this.radius = radius;
    }

    // 实现抽象方法:计算面积
    @Override
    double area() {
    return Math.PI * radius * radius;
    }

    // 实现接口方法:打印信息
    @Override
    public void print() {
    System.out.println("Circle with area: " + area());
    }

    // 主方法:测试
    public static void main(String[] args) {
    Circle circle = new Circle(5.0);
    circle.print(); // 输出 "Circle with area: 78.53981633974483"
    }
    }

2.4 静态成员

  • static 修饰的成员属于类而非对象。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /**
    * 静态成员示例:使用 static 定义类级别变量和方法
    */
    public class Counter {
    // 静态变量:所有实例共享
    public static int count = 0;

    // 静态方法:无需实例化即可调用
    public static void increment() {
    count++;
    }

    // 主方法:测试静态成员
    public static void main(String[] args) {
    // 直接调用静态方法
    Counter.increment();
    Counter.increment();
    // 访问静态变量
    System.out.println("Count: " + Counter.count); // 输出 "Count: 2"
    }
    }

3. 异常处理

3.1 异常分类

  • Checked 异常:编译时必须处理,如 IOException
  • Unchecked 异常:运行时异常,如 NullPointerException

3.2 try-catch-finally

  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
    * 异常处理示例:展示 try-catch-finally 结构
    */
    public class ExceptionExample {
    public static void main(String[] args) {
    // try 块:尝试执行可能抛出异常的代码
    try {
    int result = 10 / 0; // 除以 0 会抛出 ArithmeticException
    System.out.println(result);
    } catch (ArithmeticException e) {
    // catch 块:捕获并处理异常
    System.out.println("Error: Division by zero is not allowed.");
    } finally {
    // finally 块:无论是否发生异常都执行
    System.out.println("Exception handling completed.");
    }
    }
    }

3.3 资源管理

  • 使用 try-with-resources 自动关闭资源。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
    * 资源管理示例:使用 try-with-resources 处理资源
    */
    public class ResourceManagement {
    public static void main(String[] args) {
    // try-with-resources:自动关闭 StringReader
    try (java.io.StringReader reader = new java.io.StringReader("Sample text")) {
    int character;
    // 读取并打印字符
    while ((character = reader.read()) != -1) {
    System.out.print((char) character);
    }
    } catch (java.io.IOException e) {
    // 处理可能的 IO 异常
    System.out.println("IO Error: " + e.getMessage());
    }
    }
    }

4. 集合框架

4.1 核心接口

  • ListArrayList(动态数组),LinkedList(双向链表)
  • SetHashSet(无序,无重复),TreeSet(有序,无重复)
  • MapHashMap(键值对),TreeMap(有序键值对)

4.2 常用操作

  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    /**
    * 集合框架示例:展示 List 和 Map 的使用
    */
    import java.util.*;

    public class CollectionsExample {
    public static void main(String[] args) {
    // 创建并操作 ArrayList
    List<String> languages = new ArrayList<>();
    languages.add("Java"); // 添加元素
    languages.add("Python");
    languages.add("C++");
    System.out.println("Languages: " + languages);

    // 创建并操作 HashMap
    Map<String, Integer> scores = new HashMap<>();
    scores.put("Alice", 95); // 添加键值对
    scores.put("Bob", 87);
    System.out.println("Scores: " + scores);

    // 遍历 List
    for (String lang : languages) {
    System.out.println("Language: " + lang);
    }

    // 遍历 Map
    for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println("Student: " + entry.getKey() + ", Score: " + entry.getValue());
    }
    }
    }

5. 泛型

5.1 泛型类与方法

  • 泛型确保类型安全,避免运行时错误。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    /**
    * 泛型示例:定义泛型类 Box 并使用
    */
    public class Box<T> {
    // 泛型成员变量
    private T item;

    // 泛型方法:设置 item
    public void setItem(T item) {
    this.item = item;
    }

    // 获取 item
    public T getItem() {
    return item;
    }

    // 主方法:测试泛型
    public static void main(String[] args) {
    // 创建字符串类型的 Box
    Box<String> stringBox = new Box<>();
    stringBox.setItem("Java");
    System.out.println("Box contains: " + stringBox.getItem());

    // 创建整数类型的 Box
    Box<Integer> intBox = new Box<>();
    intBox.setItem(123);
    System.out.println("Box contains: " + intBox.getItem());
    }
    }

5.2 通配符

  • ? extends T(上界):只读。
  • ? super T(下界):只写。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
    * 通配符示例:展示泛型通配符的使用
    */
    import java.util.*;

    public class WildcardExample {
    // 使用上界通配符:只读
    public static void printList(List<? extends Number> list) {
    for (Number n : list) {
    System.out.println(n);
    }
    }

    public static void main(String[] args) {
    List<Integer> intList = Arrays.asList(1, 2, 3);
    printList(intList); // 输出 1, 2, 3
    }
    }

6. 多线程

6.1 线程创建

  • 通过 Thread 类或 Runnable 接口创建线程。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    /**
    * 多线程示例:创建并运行线程
    */
    public class ThreadExample {
    public static void main(String[] args) {
    // 使用 Lambda 表达式创建线程
    Thread thread = new Thread(() -> {
    // 线程任务:打印 0 到 2
    for (int i = 0; i < 3; i++) {
    System.out.println("Thread running: " + i);
    }
    });

    // 启动线程
    thread.start();

    // 主线程继续执行
    System.out.println("Main thread continues.");
    }
    }

6.2 同步

  • 使用 synchronized 关键字确保线程安全。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    /**
    * 线程同步示例:使用 synchronized 确保计数器线程安全
    */
    public class SynchronizedCounter {
    private int count = 0;

    // 同步方法:防止多线程并发修改
    public synchronized void increment() {
    count++;
    }

    // 获取计数器值
    public int getCount() {
    return count;
    }

    public static void main(String[] args) throws InterruptedException {
    SynchronizedCounter counter = new SynchronizedCounter();

    // 创建两个线程,分别调用 increment
    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();

    // 等待线程完成
    t1.join();
    t2.join();

    // 打印最终计数
    System.out.println("Final count: " + counter.getCount()); // 应输出 2000
    }
    }

7. 文件 I/O

7.1 流类型

  • 字节流InputStream, OutputStream
  • 字符流Reader, Writer

7.2 文件操作

  • 示例(使用 StringReader 模拟文件读取):
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    /**
    * 文件 I/O 示例:使用 try-with-resources 模拟文件读取
    */
    public class FileIOExample {
    public static void main(String[] args) {
    // try-with-resources:自动关闭 StringReader
    try (java.io.StringReader reader = new java.io.StringReader("Sample text")) {
    int character;
    // 读取并打印字符
    while ((character = reader.read()) != -1) {
    System.out.print((char) character);
    }
    } catch (java.io.IOException e) {
    // 处理可能的 IO 异常
    System.out.println("IO Error: " + e.getMessage());
    }
    }
    }

7.3 序列化

  • 将对象保存到文件或从文件恢复。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    /**
    * 序列化示例:将对象保存到流
    */
    import java.io.*;

    public class SerializationExample {
    public static void main(String[] args) {
    // 创建 Person 对象(需实现 Serializable 接口)
    Person person = new Person("Charlie", 30);

    // 序列化对象到字节流
    try (ObjectOutputStream oos = new ObjectOutputStream(
    new ByteArrayOutputStream())) {
    oos.writeObject(person);
    System.out.println("Object serialized.");
    } catch (IOException e) {
    System.out.println("Serialization error: " + e.getMessage());
    }
    }
    }

    // Person 类需实现 Serializable
    class Person implements Serializable {
    private String name;
    private int age;

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

8. Lambda 表达式与 Stream API

8.1 Lambda 表达式

  • 简化匿名函数的写法。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    /**
    * Lambda 表达式示例:遍历列表
    */
    import java.util.*;

    public class LambdaExample {
    public static void main(String[] args) {
    // 创建字符串列表
    List<String> names = Arrays.asList("Java", "Python", "C++");

    // 使用 Lambda 表达式遍历
    names.forEach(name -> System.out.println("Language: " + name));
    }
    }

8.2 Stream API

  • 用于处理集合的函数式编程。
  • 示例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    /**
    * Stream API 示例:过滤和转换集合
    */
    import java.util.*;

    public class StreamExample {
    public static void main(String[] args) {
    // 创建字符串列表
    List<String> names = Arrays.asList("Java", "Python", "C++");

    // 使用 Stream 过滤和转换
    names.stream()
    .filter(name -> name.length() > 3) // 过滤长度大于 3 的名字
    .map(name -> name.toUpperCase()) // 转换为大写
    .forEach(name -> System.out.println("Filtered and transformed: " + name));
    }
    }

9. 实践建议

  • 项目 1:命令行计算器
    • 使用集合存储历史记录,异常处理用户输入错误。
  • 项目 2:多线程文件处理器
    • 实现多线程读取和处理文本文件。
  • 项目 3:基于 Stream 的数据分析工具
    • 使用 Stream API 分析 CSV 文件中的数据。
  • 项目 4:简单 Web 应用
    • 使用 Spring Boot 搭建 RESTful API。

10. Java 与 Python 的对比

  • 类型:Java 是静态类型,变量需声明类型;Python 是动态类型。
  • 性能:Java 编译为字节码,运行速度通常快于 Python。
  • 语法:Java 语法更严格,代码更冗长;Python 简洁。
  • 并发:Java 多线程支持强大;Python 受 GIL(全局解释器锁)限制。

这份笔记涵盖了 Java 的核心概念,代码示例带有详细注释,逻辑清晰,适合从 Python 转到 Java 的学生学习和实践。