厦门工程建设招聘信息网站,网站页面排版,网站常用的字段,wordpress主题xstoreswitch表达式
使用switch时#xff0c;如果遗漏了break#xff0c;就会造成严重的逻辑错误#xff0c;而且不易在源代码中发现错误。从Java 12开始#xff0c;switch语句升级为更简洁的表达式语法#xff0c;使用类似模式匹配#xff08;Pattern Matching#xff09;的…switch表达式
使用switch时如果遗漏了break就会造成严重的逻辑错误而且不易在源代码中发现错误。从Java 12开始switch语句升级为更简洁的表达式语法使用类似模式匹配Pattern Matching的方法保证只有一种路径会被执行并且不需要break语句
public class Main {public static void main(String[] args) {String fruit apple;switch (fruit) {case apple - System.out.println(Selected apple);case pear - System.out.println(Selected pear);case mango - {System.out.println(Selected mango);System.out.println(Good choice!);}default - System.out.println(No fruit selected);}}
}
注意新语法使用-如果有多条语句需要用{}括起来。不要写break语句因为新语法只会执行匹配的语句没有穿透效应。
很多时候我们还可能用switch语句给某个变量赋值。例如
int opt;
switch (fruit) {
case apple:opt 1;break;
case pear:
case mango:opt 2;break;
default:opt 0;break;
}使用新的switch语法不但不需要break还可以直接返回值。把上面的代码改写如下
public class Main {public static void main(String[] args) {String fruit apple;int opt switch (fruit) {case apple - 1;case pear, mango - 2;default - 0;}; // 注意赋值语句要以;结束System.out.println(opt opt);}
}
这样可以获得更简洁的代码。
yield
大多数时候在switch表达式内部我们会返回简单的值。
但是如果需要复杂的语句我们也可以写很多语句放到{…}里然后用yield返回一个值作为switch语句的返回值
public class Main {public static void main(String[] args) {String fruit orange;int opt switch (fruit) {case apple - 1;case pear, mango - 2;default - {int code fruit.hashCode();yield code; // switch语句返回值}};System.out.println(opt opt);}
}