Java switch 语句完整讲解

Java switch 语句完整讲解

1. 基础语法

java 复制代码
switch(表达式){
    case 常量1:
        执行代码;
        break;
    case 常量2:
        执行代码;
        break;
    // 更多case
    default:
        都不匹配时执行;
        break;
}

规则

  1. switch() 括号里只能是:byte、short、int、char、String(JDK7+)、枚举
  2. case 后面必须是常量,不能写变量、区间
  3. break:跳出switch,不加会发生case穿透
  4. default 可选,匹配不到任何case就执行

2. 基础示例(数字匹配)

java 复制代码
int week = 3;
switch (week) {
    case 1:
        System.out.println("周一");
        break;
    case 2:
        System.out.println("周二");
        break;
    case 3:
        System.out.println("周三");
        break;
    default:
        System.out.println("无效星期");
}

3. String 字符串匹配(JDK7及以上)

java 复制代码
String grade = "A";
switch (grade) {
    case "A":
        System.out.println("优秀");
        break;
    case "B":
        System.out.println("良好");
        break;
    default:
        System.out.println("一般");
}

4. case穿透(不加break)

匹配到后会继续执行后面所有case,直到遇见break:

java 复制代码
int num = 2;
switch (num){
    case 1:
        System.out.println("1");
    case 2:
        System.out.println("2");
    case 3:
        System.out.println("3");
        break;
}
// 输出:2  3

穿透实用场景:多case共用一段代码

java 复制代码
int month = 2;
switch (month){
    case 1:
    case 2:
    case 12:
        System.out.println("冬季");
        break;
    case 3:
    case 4:
    case 5:
        System.out.println("春季");
        break;
}

5. 枚举搭配switch(专业常用)

java 复制代码
enum Season {SPRING, SUMMER, AUTUMN, WINTER}

public class Test {
    public static void main(String[] args) {
        Season s = Season.SUMMER;
        switch (s){
            case SPRING:
                System.out.println("春天");
                break;
            case SUMMER:
                System.out.println("夏天");
                break;
            default:
                System.out.println("其他季节");
        }
    }
}

6. switch新特性(Java14+ 箭头switch,无break)

不需要写break,不会穿透,更简洁:

java 复制代码
int score = 90;
switch (score / 10) {
    case 10,9 -> System.out.println("优秀");
    case 8 -> System.out.println("良好");
    case 7,6 -> System.out.println("及格");
    default -> System.out.println("不及格");
}

还可以带返回值:

java 复制代码
String res = switch (score / 10) {
    case 10,9 -> "优秀";
    case 8 -> "良好";
    default -> "不及格";
};

7. switch 和 if 区别速记

  1. switch:只做等值判断,适合固定常量多选一,分支多效率高
  2. if-else:支持区间 > < && || 复杂逻辑,万能判断

8. 常见错误

  1. case 后写变量 / 范围:case n>10: 非法
  2. 忘记break导致穿透bug
  3. switch传入long、float、double(不支持)
  4. String区分大小写,"A"和"a"不相等