1. Switch Expressions
Java 13 中引入了 Switch Expressions,这使得 Java 语言可以更好地支持 switch 语句。
语法
Switch Expressions 的语法为:
int result = switch (x) {
case 1 -> "one";
case 2 -> "two";
default -> "other";
};
其中,x
是要匹配的值,result
是 switch 表达式的结果。
实例
以下是一个 Switch Expressions 示例:
public class MySwitch {
public static void main(String[] args) {
int x = 2;
int result = switch (x) {
case 1 -> "one";
case 2 -> "two";
default -> "other";
};
System.out.println(result); // 输出 "two"
}
}
在上面的示例中,我们使用 Switch Expressions 匹配值 x
,然后我们使用 System.out.println
方法打印结果。
2. Text Blocks
Java 13 中引入了 Text Blocks,这使得 Java 语言可以更好地支持文本处理。
语法
Text Blocks 的语法为:
String text = """
Hello, World!
This is a test.
""";
其中,text
是文本块对象。
实例
以下是一个 Text Blocks 示例:
public class MyTextBlock {
public static void main(String[] args) {
String text = """
Hello, World!
This is a test.
""";
System.out.println(text); // 输出 "Hello, World!\nThis is a test."
}
}
在上面的示例中,我们使用 Text Blocks 定义文本块对象 text
,然后我们使用 System.out.println
方法打印文本块对象。
3. Pattern Matching for instanceof
Java 13 中引入了 Pattern Matching for instanceof,这使得 Java 语言可以更好地支持 instanceof 语句。
语法
Pattern Matching for instanceof 的语法为:
if (obj instanceof String s) {
System.out.println(s.length());
}
其中,obj
是要检查的对象,s
是 Pattern Matching 的变量。
实例
以下是一个 Pattern Matching for instanceof 示例:
public class MyPatternMatching {
public static void main(String[] args) {
Object obj = "Hello";
if (obj instanceof String s) {
System.out.println(s.length()); // 输出 5
}
}
}