欢迎扫码,加作者微信

Java 21 零基础入门教程

2025-11-10 23:21:19
2025-11-10 23:21:19

Java 21 零基础入门教程

本文档提供完整的 Java 21 入门教程,从环境搭建到面向对象编程,包含最新的 Java 21 特性。

目录

第一部分:Java 简介与环境搭建

1.1 什么是 Java?

Java 是一种广泛使用的编程语言,具有以下特点:

  • 跨平台:一次编写,到处运行
  • 面向对象:支持封装、继承、多态
  • 简单易学:语法类似 C++,但更简洁
  • 开源免费:拥有强大的社区支持

1.2 安装 Java 开发环境

下载 JDK 21

  1. 访问 Oracle 官网
  2. 选择对应操作系统的 JDK 21
  3. 下载并安装

配置环境变量

Windows

bash 复制代码
# 添加系统变量
JAVA_HOME = C:\Program Files\Java\jdk-21
PATH = %JAVA_HOME%\bin;...

Mac/Linux

bash 复制代码
# 编辑 ~/.bashrc 或 ~/.zshrc
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-21.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH

验证安装

打开终端/命令提示符,输入:

bash 复制代码
java -version
javac -version

第二部分:第一个 Java 程序

2.1 Hello World 程序

创建文件 HelloWorld.java

java 复制代码
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

编译和运行:

bash 复制代码
javac HelloWorld.java    # 编译
java HelloWorld          # 运行

2.2 程序结构解析

  • public class HelloWorld:定义类,类名必须与文件名相同
  • public static void main(String[] args):程序入口点
  • System.out.println():输出语句

第三部分:Java 基础语法

3.1 变量和数据类型

java 复制代码
public class Variables {
    public static void main(String[] args) {
        // 基本数据类型
        int age = 25;                    // 整数
        double price = 19.99;            // 浮点数
        char grade = 'A';                // 字符
        boolean isJavaFun = true;        // 布尔值
        String name = "张三";            // 字符串
        
        // 输出变量
        System.out.println("姓名: " + name);
        System.out.println("年龄: " + age);
        System.out.println("价格: " + price);
    }
}

3.2 数据类型详解

类型 大小 范围 示例
byte 8位 -128 ~ 127 byte b = 100;
short 16位 -32768 ~ 32767 short s = 1000;
int 32位 -2³¹ ~ 2³¹-1 int i = 100000;
long 64位 -2⁶³ ~ 2⁶³-1 long l = 100000L;
float 32位 单精度浮点数 float f = 3.14f;
double 64位 双精度浮点数 double d = 3.14;
char 16位 Unicode字符 char c = 'A';
boolean 1位 true/false boolean flag = true;

3.3 运算符

java 复制代码
public class Operators {
    public static void main(String[] args) {
        int a = 10, b = 3;
        
        // 算术运算符
        System.out.println("a + b = " + (a + b));  // 13
        System.out.println("a - b = " + (a - b));  // 7
        System.out.println("a * b = " + (a * b));  // 30
        System.out.println("a / b = " + (a / b));  // 3
        System.out.println("a % b = " + (a % b));  // 1
        
        // 比较运算符
        System.out.println("a == b: " + (a == b)); // false
        System.out.println("a > b: " + (a > b));   // true
        
        // 逻辑运算符
        boolean x = true, y = false;
        System.out.println("x && y: " + (x && y)); // false
        System.out.println("x || y: " + (x || y)); // true
        System.out.println("!x: " + (!x));         // false
    }
}

第四部分:流程控制

4.1 条件语句

java 复制代码
public class Conditionals {
    public static void main(String[] args) {
        int score = 85;
        
        // if-else 语句
        if (score >= 90) {
            System.out.println("优秀");
        } else if (score >= 80) {
            System.out.println("良好");
        } else if (score >= 60) {
            System.out.println("及格");
        } else {
            System.out.println("不及格");
        }
        
        // switch 语句 (Java 14+ 新语法)
        String grade = switch (score / 10) {
            case 10, 9 -> "A";
            case 8 -> "B";
            case 7 -> "C";
            case 6 -> "D";
            default -> "F";
        };
        System.out.println("等级: " + grade);
    }
}

4.2 循环语句

java 复制代码
public class Loops {
    public static void main(String[] args) {
        // for 循环
        System.out.println("for 循环:");
        for (int i = 1; i <= 5; i++) {
            System.out.println("数字: " + i);
        }
        
        // while 循环
        System.out.println("\nwhile 循环:");
        int j = 1;
        while (j <= 3) {
            System.out.println("计数: " + j);
            j++;
        }
        
        // do-while 循环
        System.out.println("\ndo-while 循环:");
        int k = 1;
        do {
            System.out.println("值: " + k);
            k++;
        } while (k <= 3);
        
        // 增强 for 循环
        System.out.println("\n增强 for 循环:");
        int[] numbers = {1, 2, 3, 4, 5};
        for (int num : numbers) {
            System.out.println("数组元素: " + num);
        }
    }
}

第五部分:数组

5.1 数组的基本操作

java 复制代码
public class ArraysDemo {
    public static void main(String[] args) {
        // 数组声明和初始化
        int[] numbers = new int[5];           // 长度为5的数组
        int[] scores = {90, 85, 78, 92, 88}; // 直接初始化
        
        // 访问和修改数组元素
        numbers[0] = 10;
        numbers[1] = 20;
        
        System.out.println("第一个分数: " + scores[0]);
        System.out.println("数组长度: " + scores.length);
        
        // 遍历数组
        System.out.println("所有分数:");
        for (int i = 0; i < scores.length; i++) {
            System.out.println("分数 " + i + ": " + scores[i]);
        }
        
        // 使用增强 for 循环
        System.out.println("使用增强 for 循环:");
        for (int score : scores) {
            System.out.println(score);
        }
    }
}

5.2 多维数组

java 复制代码
public class MultiDimArray {
    public static void main(String[] args) {
        // 二维数组
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        
        // 遍历二维数组
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

第六部分:方法(函数)

6.1 方法的定义和使用

java 复制代码
public class Methods {
    
    // 无返回值的方法
    public static void greet(String name) {
        System.out.println("你好, " + name + "!");
    }
    
    // 有返回值的方法
    public static int add(int a, int b) {
        return a + b;
    }
    
    // 方法重载
    public static double add(double a, double b) {
        return a + b;
    }
    
    public static void main(String[] args) {
        // 调用方法
        greet("世界");
        
        int sum1 = add(5, 3);
        double sum2 = add(2.5, 3.7);
        
        System.out.println("整数和: " + sum1);
        System.out.println("浮点数和: " + sum2);
        
        // 递归方法示例
        int factorial = factorial(5);
        System.out.println("5的阶乘: " + factorial);
    }
    
    // 递归方法
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }
        return n * factorial(n - 1);
    }
}

第七部分:面向对象编程

7.1 类和对象

java 复制代码
// 定义类
class Student {
    // 属性(字段)
    String name;
    int age;
    String studentId;
    
    // 构造方法
    public Student(String name, int age, String studentId) {
        this.name = name;
        this.age = age;
        this.studentId = studentId;
    }
    
    // 方法
    public void study() {
        System.out.println(name + "正在学习...");
    }
    
    public void displayInfo() {
        System.out.println("学生信息:");
        System.out.println("姓名: " + name);
        System.out.println("年龄: " + age);
        System.out.println("学号: " + studentId);
    }
}

public class OOPDemo {
    public static void main(String[] args) {
        // 创建对象
        Student student1 = new Student("张三", 20, "2023001");
        Student student2 = new Student("李四", 19, "2023002");
        
        // 使用对象
        student1.displayInfo();
        student1.study();
        
        student2.displayInfo();
        student2.study();
    }
}

7.2 封装

java 复制代码
class BankAccount {
    // 私有字段(封装)
    private String accountNumber;
    private double balance;
    private String owner;
    
    // 构造方法
    public BankAccount(String accountNumber, String owner, double initialBalance) {
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.balance = initialBalance;
    }
    
    // Getter 方法
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public double getBalance() {
        return balance;
    }
    
    public String getOwner() {
        return owner;
    }
    
    // 存款方法
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存款成功! 当前余额: " + balance);
        } else {
            System.out.println("存款金额必须大于0");
        }
    }
    
    // 取款方法
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取款成功! 当前余额: " + balance);
        } else {
            System.out.println("取款失败: 余额不足或金额无效");
        }
    }
}

public class EncapsulationDemo {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("123456", "张三", 1000);
        
        account.deposit(500);
        account.withdraw(200);
        account.withdraw(2000); // 应该失败
        
        System.out.println("最终余额: " + account.getBalance());
    }
}

7.3 继承

java 复制代码
// 父类
class Animal {
    String name;
    int age;
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void eat() {
        System.out.println(name + "正在吃东西");
    }
    
    public void sleep() {
        System.out.println(name + "正在睡觉");
    }
}

// 子类
class Dog extends Animal {
    String breed;
    
    public Dog(String name, int age, String breed) {
        super(name, age); // 调用父类构造方法
        this.breed = breed;
    }
    
    // 方法重写
    @Override
    public void eat() {
        System.out.println(name + "正在吃狗粮");
    }
    
    // 子类特有方法
    public void bark() {
        System.out.println(name + "在汪汪叫");
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Dog dog = new Dog("旺财", 3, "金毛");
        dog.eat();      // 调用重写的方法
        dog.sleep();    // 调用继承的方法
        dog.bark();     // 调用子类特有方法
    }
}

7.4 多态

java 复制代码
class Shape {
    public void draw() {
        System.out.println("绘制形状");
    }
    
    public double calculateArea() {
        return 0;
    }
}

class Circle extends Shape {
    double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    @Override
    public void draw() {
        System.out.println("绘制圆形,半径: " + radius);
    }
    
    @Override
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    double width, height;
    
    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }
    
    @Override
    public void draw() {
        System.out.println("绘制矩形,宽: " + width + ", 高: " + height);
    }
    
    @Override
    public double calculateArea() {
        return width * height;
    }
}

public class PolymorphismDemo {
    public static void main(String[] args) {
        // 多态示例
        Shape[] shapes = new Shape[2];
        shapes[0] = new Circle(5);
        shapes[1] = new Rectangle(4, 6);
        
        for (Shape shape : shapes) {
            shape.draw();
            System.out.println("面积: " + shape.calculateArea());
            System.out.println("---------");
        }
    }
}

第八部分:Java 21 新特性

8.1 记录类 (Records)

java 复制代码
// 传统方式
class Person {
    private final String name;
    private final int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String name() { return name; }
    public int age() { return age; }
    
    @Override
    public boolean equals(Object o) {
        // 复杂的equals实现...
    }
    
    @Override
    public int hashCode() {
        // 复杂的hashCode实现...
    }
    
    @Override
    public String toString() {
        // toString实现...
    }
}

// Java 16+ 记录类 (简化版)
record PersonRecord(String name, int age) {
    // 自动生成构造方法、getter、equals、hashCode、toString
}

public class RecordsDemo {
    public static void main(String[] args) {
        PersonRecord person = new PersonRecord("张三", 25);
        System.out.println(person.name());    // 自动生成的getter
        System.out.println(person.age());     // 自动生成的getter
        System.out.println(person);           // 自动生成的toString
    }
}

8.2 文本块 (Text Blocks)

java 复制代码
public class TextBlocks {
    public static void main(String[] args) {
        // 传统字符串
        String oldStyle = "{\n" +
                         "  \"name\": \"张三\",\n" +
                         "  \"age\": 25\n" +
                         "}";
        
        // Java 15+ 文本块
        String json = """
                      {
                        "name": "张三",
                        "age": 25
                      }
                      """;
        
        String html = """
                      <html>
                          <body>
                              <h1>欢迎</h1>
                          </body>
                      </html>
                      """;
        
        System.out.println(json);
        System.out.println(html);
    }
}

8.3 模式匹配

java 复制代码
public class PatternMatching {
    public static void main(String[] args) {
        Object obj = "Hello, Java 21!";
        
        // 传统的 instanceof
        if (obj instanceof String) {
            String str = (String) obj;
            System.out.println(str.toUpperCase());
        }
        
        // Java 16+ 模式匹配 instanceof
        if (obj instanceof String str) {
            System.out.println(str.toUpperCase());
        }
        
        // switch 表达式 + 模式匹配
        Object value = 42;
        String result = switch (value) {
            case Integer i -> "整数: " + i;
            case String s -> "字符串: " + s;
            case Double d -> "浮点数: " + d;
            default -> "未知类型";
        };
        System.out.println(result);
    }
}

第九部分:异常处理

java 复制代码
public class ExceptionHandling {
    
    public static int divide(int a, int b) {
        return a / b;
    }
    
    public static void main(String[] args) {
        // 基本的异常处理
        try {
            int result = divide(10, 0);
            System.out.println("结果: " + result);
        } catch (ArithmeticException e) {
            System.out.println("发生算术异常: " + e.getMessage());
        } finally {
            System.out.println("这是finally块,总是会执行");
        }
        
        // 多个catch块
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]); // 数组越界
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("数组索引越界: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("发生其他异常: " + e.getMessage());
        }
        
        // 抛出异常
        try {
            checkAge(15);
        } catch (IllegalArgumentException e) {
            System.out.println("捕获异常: " + e.getMessage());
        }
    }
    
    public static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("年龄必须大于等于18岁");
        }
        System.out.println("年龄验证通过");
    }
}

第十部分:集合框架

java 复制代码
import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // List - 有序集合
        List<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        list.add("橙子");
        System.out.println("List: " + list);
        
        // Set - 无序不重复集合
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(2);
        set.add(1); // 重复元素,不会被添加
        System.out.println("Set: " + set);
        
        // Map - 键值对
        Map<String, Integer> map = new HashMap<>();
        map.put("张三", 25);
        map.put("李四", 30);
        map.put("王五", 28);
        System.out.println("Map: " + map);
        System.out.println("张三的年龄: " + map.get("张三"));
        
        // 遍历集合
        System.out.println("\n遍历List:");
        for (String fruit : list) {
            System.out.println(fruit);
        }
        
        System.out.println("\n遍历Map:");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // 使用 Stream API (Java 8+)
        System.out.println("\n使用Stream:");
        list.stream()
            .filter(fruit -> fruit.length() > 2)
            .forEach(System.out::println);
    }
}

学习建议

  1. 多动手实践:每个示例代码都要亲自编写和运行
  2. 理解概念:不要死记硬背,要理解面向对象的思想
  3. 阅读文档:学会查看 Java 官方文档
  4. 做项目:尝试编写小项目来巩固知识
  5. 参与社区:加入编程社区,向他人学习和提问

下一步学习方向

  • Java 高级特性(泛型、反射、注解)
  • Java 网络编程
  • 数据库连接(JDBC)
  • 多线程编程
  • Spring 框架
  • 微服务开发

下载说明:您可以将此文档保存为 Java21-入门教程.md 文件,方便随时查阅和学习。

这个教程涵盖了 Java 21 的基础知识,适合零基础学习者。建议按照顺序学习每个部分,并完成相应的练习。祝你学习顺利!

文章目录

生成中...

扫码赞赏

感谢您的支持与鼓励

安全支付

支付赞赏

您的支持是我们前进的动力

留言
快捷金额
自定义金额
¥

安全保障

采用银行级加密技术,保障您的支付安全

暂无评论,欢迎留下你的评论

暂无评论

期待您的精彩留言!
成为第一个评论的人吧 ✨

写下第一条评论
Copyright © 2025 粤ICP备19043740号-1
🎉 今日第 1 位访客 📊 年访问量 0 💝 累计赞赏 1000+