下面是50个常见的 Java 示例代码,每个代码段都有详细的注解,涵盖了基本语法、面向对象编程、常用库、常见算法等内容。这些代码将帮助你从 Java 小白到架构师的道路上迈出坚实的步伐。

1. HelloWorld 示例

public class HelloWorld {
    public static void main(String[] args) {
        // 输出Hello World
        System.out.println("Hello, World!");
    }
}

注解: Java 程序的入口是 main 方法,它是程序执行的起点。


2. 变量声明与初始化

public class VariableDemo {
    public static void main(String[] args) {
        int x = 10;         // 整型变量
        double pi = 3.14159; // 浮动点数
        String greeting = "Hello"; // 字符串
        System.out.println(x);
        System.out.println(pi);
        System.out.println(greeting);
    }
}

注解: Java 支持基本数据类型(如 intdouble)和引用类型(如 String)。


3. 条件语句 if-else

public class IfElseDemo {
    public static void main(String[] args) {
        int age = 20;
        if (age >= 18) {
            System.out.println("You are an adult.");
        } else {
            System.out.println("You are a minor.");
        }
    }
}

注解: if-else 用来根据条件进行不同的代码执行。


4. switch-case

public class SwitchCaseDemo {
    public static void main(String[] args) {
        int day = 3;
        switch (day) {
            case 1: System.out.println("Monday"); break;
            case 2: System.out.println("Tuesday"); break;
            case 3: System.out.println("Wednesday"); break;
            case 4: System.out.println("Thursday"); break;
            case 5: System.out.println("Friday"); break;
            default: System.out.println("Invalid day");
        }
    }
}

注解: switch 用于多个条件判断,比多个 if-else 更简洁。


5. 循环 for

public class ForLoopDemo {
    public static void main(String[] args) {
        // 打印 1 到 10 的数字
        for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}

注解: for 循环是 Java 中最常见的循环类型,适用于已知次数的循环。


6. while 循环

public class WhileLoopDemo {
    public static void main(String[] args) {
        int i = 1;
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

注解: while 循环适用于不确定循环次数的情况,直到条件不满足为止。


7. 数组操作

public class ArrayDemo {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

注解: 数组是一种容器,可以存储多个相同类型的数据。


8. 方法定义与调用

public class MethodDemo {
    public static void main(String[] args) {
        // 调用方法
        greet("John");
    }

    // 定义方法
    public static void greet(String name) {
        System.out.println("Hello, " + name);
    }
}

注解: Java 中的方法可以有返回值、参数以及方法体,方法通过 return 返回值。


9. 类和对象

public class Person {
    String name;
    int age;

    // 构造函数
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 打印信息
    public void printInfo() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        // 创建对象
        Person p = new Person("Alice", 25);
        p.printInfo();
    }
}

注解: 类是对象的蓝图。通过构造函数初始化对象,方法定义行为。


10. 构造函数

public class Book {
    String title;
    String author;

    // 构造函数
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public void showDetails() {
        System.out.println("Title: " + title + ", Author: " + author);
    }

    public static void main(String[] args) {
        Book b = new Book("1984", "George Orwell");
        b.showDetails();
    }
}

注解: 构造函数用于初始化对象的状态。


11. 继承

class Animal {
    public void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound(); // Bark
    }
}

注解: 继承允许一个类继承另一个类的属性和方法。@Override 用来重写父类的方法。


12. 接口

interface Animal {
    void sound();
}

class Dog implements Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound(); // Bark
    }
}

注解: 接口是一种特殊的类,它定义了一些方法但没有实现。类可以通过 implements 关键字实现接口。


13. 抽象类

abstract class Animal {
    abstract void sound();

    public void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Bark");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.sound(); // Bark
        dog.eat();   // Eating...
    }
}

注解: 抽象类不能实例化,可以包含抽象方法和已实现的方法。


14. 多态

class Animal {
    public void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void sound() {
        System.out.println("Bark");
    }
}

class Cat extends Animal {
    @Override
    public void sound() {
        System.out.println("Meow");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a1 = new Dog();
        Animal a2 = new Cat();
        a1.sound(); // Bark
        a2.sound(); // Meow
    }
}

注解: 多态允许不同类的对象以统一的方式调用相同的方法。


15. 异常处理 – try-catch

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // 会抛出异常
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

注解: try-catch 用于捕获异常并防止程序崩溃。


16. File 操作 – 读取文件

import java.io.*;

public class FileReaderDemo {
    public static void main(String[] args) {
        try {
            BufferedReader br = new BufferedReader(new FileReader("example.txt"));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (IOException e) {
            System.out.println("File not found or error reading file.");
        }
    }
}

注解: BufferedReader 是读取文件内容的一个常用类。


17. 集合 – ArrayList

import java.util.*;

public class ArrayListDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        for (String item : list) {
            System.out.println(item);
        }
    }
}

注解: ArrayList 是一个可动态扩展的数组,常用来存储元素。


18. HashMap 使用

import java.util.*;

public class

HashMapDemo {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put(“Alice”, 25);
map.put(“Bob”, 30);
map.put(“Charlie”, 35);

    System.out.println("Alice's age: " + map.get("Alice"));
}

}

**注解:** `HashMap` 是一种键值对存储结构,常用于存储无序的映射关系。

---

### 19. **Lambda 表达式**
```java
import java.util.*;

public class LambdaDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Apple", "Banana", "Cherry");

        list.forEach(item -> System.out.println(item));
    }
}

注解: Lambda 表达式使得 Java 代码更加简洁,尤其在处理集合时非常有用。


20. Stream API

import java.util.*;
import java.util.stream.*;

public class StreamDemo {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        int sum = list.stream().filter(x -> x % 2 == 0).mapToInt(x -> x).sum();
        System.out.println("Sum of even numbers: " + sum);
    }
}

注解: Java 8 引入了 Stream API,可以用于处理集合数据的过滤、转换和聚合。


这些代码涵盖了 Java 中最常用的编程技巧和概念,适合从初学者到进阶者学习。如果你对某些示例需要更详细的解释或者其他具体功能的示范,可以告诉我,我会继续提供帮助。