Java新版switch

0

使用箭头符号可以省略break

使用yield可以有返回值

不能和return一起使用,箭头符号直接跟值可以省略yield

  • return:跳出方法
  • break:跳出switch
  • yield:跳出switch
  • ->:跳出switch

测试代码:

public int testSwitch(int key) {
	System.out.println("----------------1");
	switch (key) {
	case 1:
		System.out.println("1");
		break;
	case 2:
		System.out.println("2");
		break;
	case 3:
	case 4, 5:
		System.out.println("3");
		break;
	default:
		System.out.println("default");
		break;
	}
	System.out.println("----------------2");
	switch (key) {
	case 1:
		System.out.println("fall through=1");
	case 2:
		System.out.println("fall through=2");
	case 3:
	case 4, 5:
		System.out.println("fall through=3");
	default:
		System.out.println("fall through=default");
	}
	System.out.println("----------------3");
	switch (key) {
	case 1 -> System.out.println("1");
	case 2 -> System.out.println("2");
	case 3 -> {
		return 3;
	}
	default -> System.out.println("default");
	}
	System.out.println("----------------4");
	final int value = switch (key) {
	case 1 -> 1;
	case 2 -> {
		yield 2;
	}
	case 3, 4, 5 -> {
		yield 3;
	}
	default -> 0;
	};
	return value;
}

@Test
public void testSwitch() {
	System.out.println("return=" + testSwitch(1));
	System.out.println("================");
	System.out.println("return=" + testSwitch(2));
	System.out.println("================");
	System.out.println("return=" + testSwitch(3));
}