Skip to main content

Java 14 新特性 (EOL)

warning

生命周期结束时间(EOL): 2024/03/31

官方发布介绍页面:https://openjdk.org/projects/jdk/14/

1. Switch 表达式 (第三次预览)​

Switch 表达式在 JDK 14 中成为标准特性,允许在 switch 语句中使用表达式,并返回值。

int num = 2;
String result = switch (num) {
case 1 -> "one";
case 2 -> "two";
case 3 -> "three";
default -> "unknown";
};
System.out.println(result); // two

2. 文本块 (第二次预览)​

文本块在 JDK 14 中进行了第二次预览,允许在多行字符串中使用更简洁的语法。

String textBlock = """
Hello,
World!
""";
System.out.println(textBlock);

3. instanceof 模式匹配 (第一次预览)​

instanceof 模式匹配简化了类型检查和转换。

Object obj = "Hello, World!";
if (obj instanceof String s) {
System.out.println(s.toLowerCase()); // hello, world!
}

4. Records (第一次预览)​

Records 提供了一种简洁的方式来定义不可变数据类。

public record Point(int x, int y) {}

Point point = new Point(1, 2);
System.out.println(point.x()); // 1
System.out.println(point.y()); // 2

5. NullPointerExceptions 的改进​

改进了 NullPointerExceptions 的详细信息,提供更有用的错误消息。

String str = null;
try {
str.length();
} catch (NullPointerException e) {
e.printStackTrace();
}

6. 外部内存访问 API (第一次孵化)​

引入了外部内存访问 API,允许 Java 程序安全高效地访问外部内存。

7. ZGC: NUMA 感知和并发堆转储​

ZGC 垃圾回收器现在支持 NUMA 感知和并发堆转储。

// 使用命令行参数来启用 ZGC 的 NUMA 感知
// -XX:+UseNUMA

// 使用命令行参数来启用 ZGC 的并发堆转储
// -XX:+ZConcurrentHeapDump

8. 删除 CMS 垃圾回收器​

JDK 14 删除了 CMS 垃圾回收器。

9. 非易失性映射字节缓冲区​

引入了非易失性映射字节缓冲区,允许直接访问非易失性内存。