第一题形式化方法是一种建立在严格数学基础如数理逻辑、集合论等之上的软件开发与验证技术。它不依赖于传统的经验测试而是通过数学语言对系统进行精确的规范描述并利用数学证明或自动化验证工具来严格证明软件系统满足其需求规范从而保证系统的绝对正确性与安全性。阅读和了解形式化方法可以从以下两个个方面入手核心概念阅读重点了解前置条件、后置条件、类不变式等契约式设计概念。Java工具实践阅读并了解Java生态中的形式化规范语言OpenJML或交互式验证系统KeY。第二题public class PrimeNumberSolver { /** * 判断一个整数是否为质数 * param number 待检测的整数 * return true 如果是质数否则 false */ public static boolean isPrime(int number) { // 1. 小于等于1的数不是质数 if (number 1) { return false; } // 2. 2是唯一的偶数质数 if (number 2) { return true; } // 3. 排除所有其他偶数 if (number % 2 0) { return false; } // 4. 从3开始遍历奇数因子直到 sqrt(number) // 如果一个数 n 不是质数它一定可以分解为 a * b。 // 如果 a 和 b 都大于 sqrt(n)那么 a * b n这不可能。 // 所以只要检查到 sqrt(n) 即可。 for (int i 3; i Math.sqrt(number); i 2) { if (number % i 0) { return false; // 发现因子不是质数 } } return true; } /** * 打印指定范围 [start, end] 内的所有质数 */ public static void printPrimesInRange(int start, int end) { System.out.println(--- 正在查找 start 到 end 之间的质数 ---); int count 0; // 计数器 for (int i start; i end; i) { if (isPrime(i)) { System.out.print(i \t); count; // 每行打印5个为了美观 if (count % 5 0) { System.out.println(); } } } System.out.println(\n共找到 count 个质数。); } public static void main(String[] args) { // 测试单个数字 int testNum 29; System.out.println(testNum 是质数吗? isPrime(testNum)); System.out.println(); // 测试范围 (例如1到100) printPrimesInRange(1, 100); } }运行结果第三题场景一// 订单状态枚举 public enum OrderStatus { // 定义状态常量包含状态码和描述 PENDING_PAYMENT(1, 待支付), PAID(2, 已支付), SHIPPED(3, 已发货), COMPLETED(4, 已完成), CANCELLED(5, 已取消); private final int code; // 状态码 private final String description; // 状态描述 // 构造方法枚举的构造方法默认是private的 OrderStatus(int code, String description) { this.code code; this.description description; } // 获取状态码 public int getCode() { return code; } // 获取状态描述 public String getDescription() { return description; } // 根据状态码获取枚举实例可选方便从外部值转换 public static OrderStatus fromCode(int code) { for (OrderStatus status : OrderStatus.values()) { if (status.getCode() code) { return status; } } throw new IllegalArgumentException(未知状态码 code); } public static void main(String[] args) { // 使用枚举定义状态 OrderStatus currentStatus OrderStatus.PENDING_PAYMENT; System.out.println(当前订单状态 currentStatus.getDescription() 状态码 currentStatus.getCode() ); // 根据状态码获取状态 OrderStatus paidStatus OrderStatus.fromCode(2); System.out.println(状态码2对应的状态 paidStatus.getDescription()); // 遍历所有状态 System.out.println(\n所有订单状态); for (OrderStatus status : OrderStatus.values()) { System.out.println(status.name() - status.getDescription()); } } }运行结果场景二// 支付方式枚举策略模式 public enum PaymentStrategy { // 定义支付方式每个常量实现具体的支付逻辑 ALIPAY(支付宝) { Override public void pay(double amount) { System.out.println(使用支付宝支付 amount 元); // 实际调用支付宝接口 } }, WECHAT(微信) { Override public void pay(double amount) { System.out.println(使用微信支付 amount 元); // 实际调用微信接口 } }, BANK_CARD(银行卡) { Override public void pay(double amount) { System.out.println(使用银行卡支付 amount 元); // 实际调用银行卡接口 } }; private final String name; // 支付方式名称 // 构造方法 PaymentStrategy(String name) { this.name name; } // 策略方法处理支付逻辑 public abstract void pay(double amount); // 根据支付方式名称获取枚举实例可选 public static PaymentStrategy fromName(String name) { for (PaymentStrategy strategy : PaymentStrategy.values()) { if (strategy.getName().equals(name)) { return strategy; } } throw new IllegalArgumentException(未知支付方式 name); } public String getName() { return name; } public static void main(String[] args) { // 选择支付方式并执行 PaymentStrategy alipayStrategy PaymentStrategy.ALIPAY; alipayStrategy.pay(100.0); // 输出使用支付宝支付100.0元 PaymentStrategy wechatStrategy PaymentStrategy.fromName(微信); wechatStrategy.pay(200.0); // 输出使用微信支付200.0元 // 新增支付方式时只需添加新的枚举常量无需修改现有代码符合开闭原则 // 例如新增“PayPal”支付方式 // PAYPAL(PayPal) { Override public void pay(double amount) { System.out.println(使用PayPal支付 amount 元); } } } }运行结果场景三// 统一返回码枚举 public enum ResponseCode { // 定义返回码常量包含状态码和消息 SUCCESS(200, 操作成功), PARAM_ERROR(400, 参数错误), UNAUTHORIZED(401, 未授权请先登录), FORBIDDEN(403, 禁止访问), NOT_FOUND(404, 资源不存在), SERVER_ERROR(500, 服务器内部错误), BUSINESS_ERROR(1001, 业务逻辑错误); private final int code; // 返回码 private final String message; // 返回消息 // 构造方法 ResponseCode(int code, String message) { this.code code; this.message message; } // 获取返回码 public int getCode() { return code; } // 获取返回消息 public String getMessage() { return message; } // 根据返回码获取枚举实例可选 public static ResponseCode fromCode(int code) { for (ResponseCode responseCode : ResponseCode.values()) { if (responseCode.getCode() code) { return responseCode; } } // 返回默认的服务器错误码 return SERVER_ERROR; } // 统一返回结果类可选封装返回码和消息 public static class Result { private int code; private String message; private Object data; public Result(int code, String message, Object data) { this.code code; this.message message; this.data data; } // 成功返回 public static Result success(Object data) { return new Result(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMessage(), data); } // 错误返回 public static Result error(ResponseCode responseCode) { return new Result(responseCode.getCode(), responseCode.getMessage(), null); } // 自定义错误返回 public static Result error(int code, String message) { return new Result(code, message, null); } Override public String toString() { return Result{ code code , message message , data data }; } } public static void main(String[] args) { // 模拟接口返回 System.out.println(ResponseCode.SUCCESS.getMessage() 码 ResponseCode.SUCCESS.getCode() ); // 操作成功码200 System.out.println(ResponseCode.PARAM_ERROR.getMessage() 码 ResponseCode.PARAM_ERROR.getCode() ); // 参数错误码400 // 使用统一返回结果类 Result successResult Result.success(new String[]{用户1, 用户2}); System.out.println(successResult); // Result{code200, message操作成功, data[用户1, 用户2]} Result errorResult Result.error(ResponseCode.UNAUTHORIZED); System.out.println(errorResult); // Result{code401, message未授权请先登录, datanull} // 根据返回码获取消息 ResponseCode code500 ResponseCode.fromCode(500); System.out.println(code500.getMessage()); // 服务器内部错误 } }运行结果第四题// 1. 定义一个函数式接口也可以用普通接口 // 作用代表我们要执行的“具体业务逻辑” interface Task { void execute(); } public class ExecutionTimer { /** * 核心方法计算任务执行时间 * param task 传入的匿名内部类对象实现了 Task 接口 */ public static void measureTime(Task task) { long startTime System.currentTimeMillis(); // 记录开始时间 // 执行具体的业务逻辑 task.execute(); long endTime System.currentTimeMillis(); // 记录结束时间 double duration (endTime - startTime) / 1000.0; // 计算耗时转换为秒 System.out.println( 方法执行耗时: duration 秒); } public static void main(String[] args) { System.out.println(--- 开始测试 ---); // 【重点】这里使用了匿名内部类 // 我们没有单独创建一个类去实现 Task 接口而是直接在这里 new 了一个实现类 measureTime(new Task() { Override public void execute() { // 模拟一个耗时的操作比如处理大量数据或休眠 try { System.out.println(正在执行耗时任务...); Thread.sleep(2500); // 模拟休眠 2.5 秒 } catch (InterruptedException e) { e.printStackTrace(); } } }); System.out.println(--- 测试结束 ---); } }运行结果第五题答案Java反射机制是程序在运行时动态获取类的信息如字段、方法、构造器并操作对象如创建实例、调用方法、访问属性的能力。它使Java程序具备“自我审视”和“动态行为”的特性是框架、依赖注入、序列化等高级功能的核心基础。第六题文本文件复制import java.io.*; public class TextFileCopy { public static void main(String[] args) { // 定义源文件和目标文件路径 String sourcePath source.txt; // 请确保这个文件存在 String targetPath dest_text.txt; // 使用 try-with-resources 自动关闭流防止资源泄露 try (BufferedReader reader new BufferedReader(new FileReader(sourcePath)); BufferedWriter writer new BufferedWriter(new FileWriter(targetPath))) { String line; // readLine() 每次读取一行文本不包含换行符 while ((line reader.readLine()) ! null) { writer.write(line); writer.newLine(); // 写入换行符保持原文格式 } System.out.println(文本文件复制成功); } catch (IOException e) { e.printStackTrace(); } } }运行结果任意文件复制import java.io.*; public class AnyFileCopy { public static void main(String[] args) { // 这里可以替换为任何文件的路径例如 photo.jpg 或 music.mp3 String sourcePath photo.jpg; String targetPath copy_photo.jpg; try (BufferedInputStream bis new BufferedInputStream(new FileInputStream(sourcePath)); BufferedOutputStream bos new BufferedOutputStream(new FileOutputStream(targetPath))) { // 定义一个字节数组作为缓冲区通常设置为 1024 的倍数如 8KB byte[] buffer new byte[8192]; int bytesRead; // 循环读取直到文件末尾返回 -1 while ((bytesRead bis.read(buffer)) ! -1) { // 将读取到的有效字节写入目标文件 bos.write(buffer, 0, bytesRead); } System.out.println(任意文件复制成功); } catch (IOException e) { e.printStackTrace(); } } }运行结果第七题继承 Thread 类// 定义一个类继承 Thread class MyThread extends Thread { Override public void run() { System.out.println(我是继承 Thread 类的线程 Thread.currentThread().getName()); } } public class ThreadDemo { public static void main(String[] args) { // 直接实例化并启动 MyThread t1 new MyThread(); t1.start(); } }运行结果实现 Runnable 接口// 定义一个类实现 Runnable 接口 class MyRunnable implements Runnable { Override public void run() { System.out.println(我是实现 Runnable 接口的线程 Thread.currentThread().getName()); } } public class RunnableDemo { public static void main(String[] args) { // 1. 创建任务对象 MyRunnable task new MyRunnable(); // 2. 将任务包装进 Thread 对象中 Thread t1 new Thread(task); t1.start(); } }运行结果