Java 13 新特性(JKD13)

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
        }
    }
}
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值