nav_path: java_instant_reference


下面是Java速查手册的一个大纲,涵盖了基本语法、常用类和方法、异常处理等内容。这样的手册对初学者和有经验的开发者都非常有用,可以节省查找文档和在线搜索的时间。

1. 基本语法

1.1 数据类型

  • 基本数据类型
  1. byte b = 127;
  2. short s = 32767;
  3. int i = 2147483647;
  4. long l = 9223372036854775807L;
  5. float f = 3.14f;
  6. double d = 3.141592653589793;
  7. char c = 'A';
  8. boolean bool = true;
  • 引用数据类型
  1. String str = "Hello, World!";
  2. int[] arr = {1, 2, 3, 4, 5};

1.2 变量与常量

  • 变量声明
  1. int a = 10;
  • 常量声明
  1. final int CONSTANT = 100;

1.3 运算符

  • 算术运算符
  1. int sum = a + b;
  2. int diff = a - b;
  3. int product = a * b;
  4. int quotient = a / b;
  5. int remainder = a % b;
  • 比较运算符
  1. boolean isEqual = (a == b);
  2. boolean isNotEqual = (a != b);
  3. boolean isGreater = (a > b);
  4. boolean isLesser = (a < b);
  5. boolean isGreaterOrEqual = (a >= b);
  6. boolean isLesserOrEqual = (a <= b);
  • 逻辑运算符
  1. boolean and = (a > b && c > d);
  2. boolean or = (a > b || c > d);
  3. boolean not = !(a > b);

1.4 控制结构

  • 条件语句
  1. if (a > b) {
  2. System.out.println("a is greater than b");
  3. } else if (a < b) {
  4. System.out.println("a is less than b");
  5. } else {
  6. System.out.println("a is equal to b");
  7. }
  • 循环语句
  1. // for循环
  2. for (int i = 0; i < 10; i++) {
  3. System.out.println(i);
  4. }
  5. // while循环
  6. int i = 0;
  7. while (i < 10) {
  8. System.out.println(i);
  9. i++;
  10. }
  11. // do-while循环
  12. int j = 0;
  13. do {
  14. System.out.println(j);
  15. j++;
  16. } while (j < 10);

2. 面向对象编程

2.1 类与对象

  • 类的定义
  1. public class Person {
  2. private String name;
  3. private int age;
  4. // 构造方法
  5. public Person(String name, int age) {
  6. this.name = name;
  7. this.age = age;
  8. }
  9. // Getter和Setter方法
  10. public String getName() {
  11. return name;
  12. }
  13. public void setName(String name) {
  14. this.name = name;
  15. }
  16. public int getAge() {
  17. return age;
  18. }
  19. public void setAge(int age) {
  20. this.age = age;
  21. }
  22. // 普通方法
  23. public void introduce() {
  24. System.out.println("Hi, my name is " + name + " and I am " + age + " years old.");
  25. }
  26. }
  • 对象的创建
  1. Person person = new Person("Alice", 30);
  2. person.introduce();

2.2 继承

  • 继承的使用
  1. public class Student extends Person {
  2. private String studentId;
  3. public Student(String name, int age, String studentId) {
  4. super(name, age);
  5. this.studentId = studentId;
  6. }
  7. public String getStudentId() {
  8. return studentId;
  9. }
  10. public void setStudentId(String studentId) {
  11. this.studentId = studentId;
  12. }
  13. @Override
  14. public void introduce() {
  15. super.introduce();
  16. System.out.println("My student ID is " + studentId);
  17. }
  18. }

2.3 多态

  • 多态的使用
  1. public class Animal {
  2. public void makeSound() {
  3. System.out.println("Some generic animal sound");
  4. }
  5. }
  6. public class Dog extends Animal {
  7. @Override
  8. public void makeSound() {
  9. System.out.println("Bark");
  10. }
  11. }
  12. public class Cat extends Animal {
  13. @Override
  14. public void makeSound() {
  15. System.out.println("Meow");
  16. }
  17. }
  18. public class Main {
  19. public static void main(String[] args) {
  20. Animal myDog = new Dog();
  21. Animal myCat = new Cat();
  22. myDog.makeSound(); // 输出:Bark
  23. myCat.makeSound(); // 输出:Meow
  24. }
  25. }

3. 常用类与方法

3.1 字符串处理

  • 字符串拼接
  1. String greeting = "Hello" + " " + "World!";
  • 字符串长度
  1. int length = greeting.length();
  • 字符串比较
  1. boolean isEqual = greeting.equals("Hello World!");
  • 子字符串
  1. String subStr = greeting.substring(0, 5);

3.2 集合框架

  • ArrayList
  1. List<String> list = new ArrayList<>();
  2. list.add("Apple");
  3. list.add("Banana");
  4. list.add("Cherry");
  5. for (String fruit : list) {
  6. System.out.println(fruit);
  7. }
  • HashMap
  1. Map<String, Integer> map = new HashMap<>();
  2. map.put("Apple", 1);
  3. map.put("Banana", 2);
  4. map.put("Cherry", 3);
  5. for (Map.Entry<String, Integer> entry : map.entrySet()) {
  6. System.out.println(entry.getKey() + ": " + entry.getValue());
  7. }

4. 异常处理

4.1 try-catch块

  • 基本用法
  1. try {
  2. int result = 10 / 0;
  3. } catch (ArithmeticException e) {
  4. System.out.println("Cannot divide by zero");
  5. }

4.2 自定义异常

  • 定义和使用自定义异常
  1. public class CustomException extends Exception {
  2. public CustomException(String message) {
  3. super(message);
  4. }
  5. }
  6. public class Main {
  7. public static void main(String[] args) {
  8. try {
  9. throw new CustomException("This is a custom exception");
  10. } catch (CustomException e) {
  11. System.out.println(e.getMessage());
  12. }
  13. }
  14. }

5. 输入输出(I/O)

5.1 文件操作

  • 读取文件
  1. import java.io.BufferedReader;
  2. import java.io.FileReader;
  3. import java.io.IOException;
  4. public class FileReadExample {
  5. public static void main(String[] args) {
  6. try (BufferedReader br = new BufferedReader(new FileReader("example.txt"))) {
  7. String line;
  8. while ((line = br.readLine()) != null) {
  9. System.out.println(line);
  10. }
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }
  • 写入文件
  1. import java.io.BufferedWriter;
  2. import java.io.FileWriter;
  3. import java.io.IOException;
  4. public class FileWriteExample {
  5. public static void main(String[] args) {
  6. try (BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"))) {
  7. bw.write("Hello, World!");
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }

6. 并发编程

6.1 创建线程

  • 继承Thread类
  1. public class MyThread extends Thread {
  2. @Override
  3. public void run() {
  4. System.out.println("Thread is running");
  5. }
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. MyThread thread = new MyThread();
  10. thread.start();
  11. }
  12. }
  • 实现Runnable接口
  1. public class MyRunnable implements Runnable {
  2. @Override
  3. public void run() {
  4. System.out.println("Thread is running");
  5. }
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. Thread thread = new Thread

好的,下面是Java速查手册的继续部分。


6. 并发编程 (续)

6.1 创建线程

  • 实现Runnable接口
  1. public class MyRunnable implements Runnable {
  2. @Override
  3. public void run() {
  4. System.out.println("Thread is running");
  5. }
  6. }
  7. public class Main {
  8. public static void main(String[] args) {
  9. Thread thread = new Thread(new MyRunnable());
  10. thread.start();
  11. }
  12. }

6.2 并发工具类

  • ExecutorService
  1. import java.util.concurrent.ExecutorService;
  2. import java.util.concurrent.Executors;
  3. public class Main {
  4. public static void main(String[] args) {
  5. ExecutorService executorService = Executors.newFixedThreadPool(2);
  6. executorService.submit(new MyRunnable());
  7. executorService.submit(new MyRunnable());
  8. executorService.shutdown();
  9. }
  10. }
  • CountDownLatch
  1. import java.util.concurrent.CountDownLatch;
  2. public class Worker implements Runnable {
  3. private CountDownLatch latch;
  4. public Worker(CountDownLatch latch) {
  5. this.latch = latch;
  6. }
  7. @Override
  8. public void run() {
  9. System.out.println(Thread.currentThread().getName() + " is working");
  10. try {
  11. Thread.sleep((int) (Math.random() * 1000));
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. latch.countDown();
  16. System.out.println(Thread.currentThread().getName() + " finished working");
  17. }
  18. }
  19. public class Main {
  20. public static void main(String[] args) {
  21. CountDownLatch latch = new CountDownLatch(3);
  22. new Thread(new Worker(latch)).start();
  23. new Thread(new Worker(latch)).start();
  24. new Thread(new Worker(latch)).start();
  25. try {
  26. latch.await();
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. System.out.println("All workers finished. Main thread continues.");
  31. }
  32. }

7. 网络编程

7.1 创建服务器

  • 简单服务器
  1. import java.io.IOException;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. public class SimpleServer {
  5. public static void main(String[] args) {
  6. try (ServerSocket serverSocket = new ServerSocket(8080)) {
  7. System.out.println("Server is listening on port 8080");
  8. while (true) {
  9. Socket socket = serverSocket.accept();
  10. System.out.println("New client connected");
  11. }
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

7.2 创建客户端

  • 简单客户端
  1. import java.io.IOException;
  2. import java.net.Socket;
  3. public class SimpleClient {
  4. public static void main(String[] args) {
  5. try (Socket socket = new Socket("localhost", 8080)) {
  6. System.out.println("Connected to the server");
  7. } catch (IOException e) {
  8. e.printStackTrace();
  9. }
  10. }
  11. }

8. 数据库操作

8.1 使用JDBC连接数据库

  • 连接数据库
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. public class DatabaseConnection {
  5. public static void main(String[] args) {
  6. String url = "jdbc:mysql://localhost:3306/mydatabase";
  7. String user = "root";
  8. String password = "password";
  9. try (Connection conn = DriverManager.getConnection(url, user, password)) {
  10. if (conn != null) {
  11. System.out.println("Connected to the database");
  12. }
  13. } catch (SQLException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }

8.2 执行SQL查询

  • 查询数据
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. public class DatabaseQuery {
  7. public static void main(String[] args) {
  8. String url = "jdbc:mysql://localhost:3306/mydatabase";
  9. String user = "root";
  10. String password = "password";
  11. try (Connection conn = DriverManager.getConnection(url, user, password);
  12. Statement stmt = conn.createStatement()) {
  13. String sql = "SELECT id, name, age FROM users";
  14. ResultSet rs = stmt.executeQuery(sql);
  15. while (rs.next()) {
  16. int id = rs.getInt("id");
  17. String name = rs.getString("name");
  18. int age = rs.getInt("age");
  19. System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
  20. }
  21. } catch (SQLException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }

8.3 更新数据

  • 更新数据
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. public class DatabaseUpdate {
  6. public static void main(String[] args) {
  7. String url = "jdbc:mysql://localhost:3306/mydatabase";
  8. String user = "root";
  9. String password = "password";
  10. try (Connection conn = DriverManager.getConnection(url, user, password);
  11. Statement stmt = conn.createStatement()) {
  12. String sql = "UPDATE users SET age = 30 WHERE id = 1";
  13. int rowsAffected = stmt.executeUpdate(sql);
  14. System.out.println("Rows affected: " + rowsAffected);
  15. } catch (SQLException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }

8.4 插入数据

  • 插入数据
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. public class DatabaseInsert {
  6. public static void main(String[] args) {
  7. String url = "jdbc:mysql://localhost:3306/mydatabase";
  8. String user = "root";
  9. String password = "password";
  10. try (Connection conn = DriverManager.getConnection(url, user, password);
  11. Statement stmt = conn.createStatement()) {
  12. String sql = "INSERT INTO users (name, age) VALUES ('John Doe', 25)";
  13. int rowsAffected = stmt.executeUpdate(sql);
  14. System.out.println("Rows affected: " + rowsAffected);
  15. } catch (SQLException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }

8.5 删除数据

  • 删除数据
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.SQLException;
  4. import java.sql.Statement;
  5. public class DatabaseDelete {
  6. public static void main(String[] args) {
  7. String url = "jdbc:mysql://localhost:3306/mydatabase";
  8. String user = "root";
  9. String password = "password";
  10. try (Connection conn = DriverManager.getConnection(url, user, password);
  11. Statement stmt = conn.createStatement()) {
  12. String sql = "DELETE FROM users WHERE id = 1";
  13. int rowsAffected = stmt.executeUpdate(sql);
  14. System.out.println("Rows affected: " + rowsAffected);
  15. } catch (SQLException e) {
  16. e.printStackTrace();
  17. }
  18. }
  19. }

9. 网络编程

9.1 创建服务器

  • 简单服务器
  1. import java.io.IOException;
  2. import java.net.ServerSocket;
  3. import java.net.Socket;
  4. public class SimpleServer {
  5. public static void main(String[] args) {
  6. try (ServerSocket serverSocket = new ServerSocket(8080)) {
  7. System.out.println("Server is listening on port 8080");
  8. while (true) {
  9. Socket socket = serverSocket.accept();
  10. System.out.println("New client connected");
  11. }
  12. } catch (IOException e) {
  13. e.printStackTrace();
  14. }
  15. }
  16. }

9.2 创建客户端

  • 简单客户端
  1. import java.io.IOException;
  2. import java.net.Socket;
  3. public class SimpleClient {
  4. public static void main(String[] args) {
  5. try (Socket socket = new Socket("localhost", 8080)) {
  6. System.out.println("Connected to the server");
  7. } catch (IOException e) {
  8. e.printStackTrace();
  9. }
  10. }
  11. }

10. Web开发

10.1 创建Servlet

  • 简单Servlet
  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.annotation.WebServlet;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. @WebServlet("/hello")
  9. public class HelloServlet extends HttpServlet {
  10. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  11. throws ServletException, IOException {
  12. response.setContentType("text/html");
  13. PrintWriter out = response.getWriter();
  14. out.println("<html><body>");
  15. out.println("<h1>Hello, World!</h1>");
  16. out.println("</body></html>");
  17. }
  18. }

10.2 创建JSP页面

  • 简单JSP页面
  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>JSP Example</title>
  5. </head>
  6. <body>
  7. <h1>Hello, JSP!</h1>
  8. <%
  9. // 在JSP中嵌入Java代码
  10. String message = "Welcome to JSP!";
  11. out.println("<p>" + message + "</p>");
  12. %>
  13. </body>
  14. </html>

10.3 Spring Boot

  • 创建Spring Boot应用主类
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. @SpringBootApplication
  4. public class MyApp {
  5. public static void main(String[] args) {
  6. SpringApplication.run(MyApp.class, args);
  7. }
  8. }
  • 创建一个简单的REST控制器
  1. import org.springframework.web.bind.annotation.GetMapping;
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. import org.springframework.web.bind.annotation.RestController;
  4. @RestController
  5. @RequestMapping("/api")
  6. public class GreetingController {
  7. @GetMapping("/greeting")
  8. public String greeting() {
  9. return "Hello, RESTful Web Service!";
  10. }
  11. }
  • 配置文件(application.properties)
  1. server.port=8080

10.4 Spring MVC

  • 创建控制器类
  1. import org.springframework.stereotype.Controller;
  2. import org.springframework.ui.Model;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. @Controller
  6. @RequestMapping("/home")
  7. public class HomeController {
  8. @GetMapping
  9. public String home(Model model) {
  10. model.addAttribute("message", "Welcome to Spring MVC!");
  11. return "home";
  12. }
  13. }
  • 创建视图模板(home.html)
  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <title>Home</title>
  5. </head>
  6. <body>
  7. <h1 th:text="${message}">Welcome to Spring MVC!</h1>
  8. </body>
  9. </html>

11. 测试

11.1 使用JUnit

  • 创建一个简单的JUnit测试
  1. import static org.junit.jupiter.api.Assertions.assertEquals;
  2. import org.junit.jupiter.api.Test;
  3. public class CalculatorTest {
  4. @Test
  5. public void testAddition() {
  6. Calculator calculator = new Calculator();
  7. int result = calculator.add(2, 3);
  8. assertEquals(5, result, "2 + 3 should equal 5");
  9. }
  10. }
  11. class Calculator {
  12. public int add(int a, int b) {
  13. return a + b;
  14. }
  15. }

11.2 使用Mockito

  • 创建一个Mockito测试
  1. import static org.mockito.Mockito.*;
  2. import org.junit.jupiter.api.Test;
  3. import org.mockito.InjectMocks;
  4. import org.mockito.Mock;
  5. import org.mockito.MockitoAnnotations;
  6. public class UserServiceTest {
  7. @Mock
  8. private UserRepository userRepository;
  9. @InjectMocks
  10. private UserService userService;
  11. @Test
  12. public void testFindUserById() {
  13. MockitoAnnotations.openMocks(this);
  14. User user = new User("John");
  15. when(userRepository.findById(1L)).thenReturn(Optional.of(user));
  16. User result = userService.findUserById(1L);
  17. assertEquals("John", result.getName());
  18. }
  19. }
  20. class User {
  21. private String name;
  22. public User(String name) {
  23. this.name = name;
  24. }
  25. public String getName() {
  26. return name;
  27. }
  28. }
  29. interface UserRepository {
  30. Optional<User> findById(Long id);
  31. }
  32. class UserService {
  33. private UserRepository userRepository;
  34. public UserService(UserRepository userRepository) {
  35. this.userRepository = userRepository;
  36. }
  37. public User findUserById(Long id) {
  38. return userRepository.findById(id).orElse(null);
  39. }
  40. }

12. 常见问题

12.1 NullPointerException

  • 处理NullPointerException
  1. String str = null;
  2. if (str != null) {
  3. System.out.println(str.length());
  4. } else {
  5. System.out.println("String is null");
  6. }

12.2 ClassCastException

  • 处理ClassCastException
  1. Object obj = "Hello";
  2. if (obj instanceof Integer) {
  3. Integer num = (Integer) obj;
  4. } else {
  5. System.out.println("Object is not an Integer");
  6. }

12.3 ArrayIndexOutOfBoundsException

  • 处理ArrayIndexOutOfBoundsException
  1. int[] arr = {1, 2, 3};
  2. int index = 3;
  3. if (index >= 0 && index < arr.length) {
  4. System.out.println(arr[index]);
  5. } else {
  6. System.out.println("Index is out of bounds");
  7. }