2025-04-10
编程
00

目录

1. 基本结构
2. 数据类型
基本类型:
3. 变量与常量
4. 运算符
5. 控制流语句
条件语句
循环
6. 数组
7. 函数
8. 面向对象编程(OOP)
类与对象
继承
9. 异常处理
10. 输入输出
11. 标准库
集合框架
12. 文件操作
写入文件
读取文件
13. 泛型(Generics)
泛型类
泛型方法
14. 集合框架进阶
使用 ArrayList
使用 HashSet
使用 HashMap
15. 多线程编程
继承 Thread 类
实现 Runnable 接口
16. 并发工具
使用 ExecutorService
使用 CountDownLatch
17. 输入输出流(I/O Streams)
使用 BufferedReader 和 BufferedWriter
18. 反射机制
19. 注解(Annotations)
自定义注解
20. Lambda 表达式与函数式接口
函数式接口示例
使用 Lambda 表达式遍历集合

Java 是一种广泛使用的面向对象的编程语言,以其“编写一次,到处运行”的特性而闻名。

1. 基本结构

每个 Java 程序至少包含一个类,并且程序从 main 方法开始执行。

java
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
  • public class HelloWorld:定义了一个名为 HelloWorld 的公共类。
  • public static void main(String[] args):这是 Java 应用程序的入口点。
  • System.out.println():用于打印输出到控制台。

2. 数据类型

Java 有两大类数据类型:基本类型和引用类型(对象)。

基本类型:

  • 整型:byte, short, int, long
  • 浮点型:float, double
  • 字符型:char
  • 布尔型:boolean
java
int age = 25; double height = 5.7; char initial = 'J'; boolean isStudent = true;

3. 变量与常量

变量存储数据,可以随时改变其值;常量使用 final 关键字声明,一旦赋值后不可更改。

java
final double PI = 3.14159; // 常量 int x = 10; // 变量 x = 20; // 合法 // PI = 3.14; // 错误,不能修改常量

4. 运算符

Java 支持多种运算符,包括算术运算符、关系运算符、逻辑运算符等。

java
int a = 10, b = 5; System.out.println(a + b); // 输出: 15 System.out.println(a > b); // 输出: true System.out.println((a > b) && (a != b)); // 输出: true

5. 控制流语句

条件语句

java
if (age >= 18) { System.out.println("Adult"); } else if (age >= 13) { System.out.println("Teenager"); } else { System.out.println("Child"); }

循环

  • for 循环:
java
for (int i = 0; i < 5; i++) { System.out.println(i); }
  • while 循环:
java
int count = 0; while (count < 5) { System.out.println(count); count++; }
  • do...while 循环:
java
int number = 0; do { System.out.println(number); number++; } while (number < 5);

6. 数组

数组是一种容器对象,用于存储固定大小的同种类型的元素。

java
int[] numbers = new int[5]; numbers[0] = 1; numbers[1] = 2; System.out.println(numbers[0]); // 输出: 1 // 或者直接初始化 int[] nums = {1, 2, 3, 4, 5};

7. 函数

在 Java 中称为方法,用于封装代码块以实现特定功能。

java
public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(5, 3); System.out.println("Result: " + result); // 输出: Result: 8 }

8. 面向对象编程(OOP)

Java 是面向对象的语言,支持类、对象、继承、封装、多态等概念。

类与对象

java
class Person { String name; int age; void introduce() { System.out.println("My name is " + name + " and I am " + age + " years old."); } } public class Main { public static void main(String[] args) { Person person = new Person(); person.name = "Alice"; person.age = 30; person.introduce(); // 输出: My name is Alice and I am 30 years old. } }

继承

java
class Student extends Person { String grade; void study() { System.out.println(name + " is studying in grade " + grade); } } public class Main { public static void main(String[] args) { Student student = new Student(); student.name = "Bob"; student.age = 15; student.grade = "10"; student.introduce(); // 调用了父类的方法 student.study(); // 调用了子类的方法 } }

9. 异常处理

Java 提供了异常处理机制来捕获并处理错误。

java
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("This block always executes."); }

10. 输入输出

使用 Scanner 类进行输入操作,System.out 进行输出操作。

java
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your name: "); String name = scanner.nextLine(); System.out.println("Hello, " + name); } }

11. 标准库

Java 提供了丰富的标准库,例如 java.util 包中的集合框架、日期时间 API 等。

集合框架

  • ArrayList 示例:
java
import java.util.ArrayList; ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); System.out.println(fruits.get(0)); // 输出: Apple
  • HashMap 示例:
java
import java.util.HashMap; HashMap<String, Integer> map = new HashMap<>(); map.put("Alice", 30); map.put("Bob", 25); System.out.println(map.get("Alice")); // 输出: 30

12. 文件操作

使用 java.io 包中的类来进行文件读写操作。

写入文件

java
import java.io.FileWriter; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("example.txt"); writer.write("Hello, File!"); writer.close(); } }

读取文件

java
import java.io.FileReader; import java.io.BufferedReader; import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader("example.txt")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } }

13. 泛型(Generics)

泛型允许你在定义类、接口和方法时使用类型参数,使得代码可以在多种数据类型上复用,同时保持类型安全。

泛型类

java
public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box<Integer> integerBox = new Box<>(); integerBox.set(10); System.out.println(integerBox.get()); // 输出: 10 Box<String> stringBox = new Box<>(); stringBox.set("Hello"); System.out.println(stringBox.get()); // 输出: Hello } }

泛型方法

java
public class Util { public static <T> void printArray(T[] array) { for (T element : array) { System.out.print(element + " "); } System.out.println(); } public static void main(String[] args) { Integer[] intArray = {1, 2, 3}; String[] stringArray = {"A", "B", "C"}; Util.printArray(intArray); // 输出: 1 2 3 Util.printArray(stringArray); // 输出: A B C } }

14. 集合框架进阶

Java 提供了丰富的集合框架,包括 List, Set, Map 等接口及其具体实现。

使用 ArrayList

java
import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); System.out.println(list.get(0)); // 输出: Apple } }

使用 HashSet

java
import java.util.HashSet; import java.util.Set; public class Main { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // 重复元素不会被添加 System.out.println(set.size()); // 输出: 2 } }

使用 HashMap

java
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Alice", 30); map.put("Bob", 25); System.out.println(map.get("Alice")); // 输出: 30 } }

15. 多线程编程

Java 提供了多种方式来实现多线程编程,包括继承 Thread 类和实现 Runnable 接口。

继承 Thread

java
class MyThread extends Thread { public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getId() + " Value " + i); } } } public class Main { public static void main(String[] args) { MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); thread1.start(); thread2.start(); } }

实现 Runnable 接口

java
class MyRunnable implements Runnable { public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getId() + " Value " + i); } } } public class Main { public static void main(String[] args) { Thread thread1 = new Thread(new MyRunnable()); Thread thread2 = new Thread(new MyRunnable()); thread1.start(); thread2.start(); } }

16. 并发工具

Java 提供了丰富的并发工具包 java.util.concurrent,用于简化并发编程。

使用 ExecutorService

java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); for (int i = 0; i < 5; i++) { executor.execute(new MyRunnable()); } executor.shutdown(); } }

使用 CountDownLatch

java
import java.util.concurrent.CountDownLatch; public class Main { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is working."); latch.countDown(); }).start(); } latch.await(); // 等待所有线程完成 System.out.println("All tasks are done."); } }

17. 输入输出流(I/O Streams)

Java 提供了多种 I/O 流用于处理文件和其他外部资源的读写操作。

使用 BufferedReaderBufferedWriter

java
import java.io.*; public class Main { public static void main(String[] args) throws IOException { FileWriter writer = new FileWriter("example.txt"); BufferedWriter bufferedWriter = new BufferedWriter(writer); bufferedWriter.write("Hello, File!"); bufferedWriter.close(); FileReader reader = new FileReader("example.txt"); BufferedReader bufferedReader = new BufferedReader(reader); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); } }

18. 反射机制

反射允许在运行时动态地获取类的信息或调用对象的方法。

java
import java.lang.reflect.Method; public class Main { public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("Person"); Object obj = cls.getDeclaredConstructor().newInstance(); Method method = cls.getMethod("setName", String.class); method.invoke(obj, "Alice"); Method getNameMethod = cls.getMethod("getName"); System.out.println(getNameMethod.invoke(obj)); // 输出: Alice } } class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }

19. 注解(Annotations)

注解提供了一种元数据机制,可用于编译时检查或运行时处理。

自定义注解

java
import java.lang.annotation.*; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface TestAnnotation { String value(); } public class Main { @TestAnnotation(value = "TestMethod") public void myMethod() { System.out.println("This is a test method."); } public static void main(String[] args) throws Exception { Method method = Main.class.getMethod("myMethod"); if (method.isAnnotationPresent(TestAnnotation.class)) { TestAnnotation annotation = method.getAnnotation(TestAnnotation.class); System.out.println(annotation.value()); // 输出: TestMethod } } }

20. Lambda 表达式与函数式接口

Java 8 引入了 Lambda 表达式,简化了匿名内部类的编写,并支持函数式编程。

函数式接口示例

java
@FunctionalInterface interface MyFunction { void apply(); } public class Main { public static void main(String[] args) { MyFunction function = () -> System.out.println("Lambda expression"); function.apply(); // 输出: Lambda expression } }

使用 Lambda 表达式遍历集合

java
import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); names.forEach(name -> System.out.println(name)); // 或者使用方法引用 names.forEach(System.out::println); } }