switch-case

本文详细介绍了Java中的switch-case语句的一般形式、使用注意事项,并与C语言中的switch-case进行了对比。特别强调了编译时常量的重要性以及不同类型的表达式如何被自动提升为int型。同时,文章还通过示例展示了Java枚举与C枚举的不同用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


Java的switch-case与C中的switch-case基本一致,但还是有些地方需要注意的。


switch-case语句的一般形式为:

switch (expression) {
case constant1: code block
case constant2: code block
default: code block
}

(1) A switch's expression must evaluate to a char, byte, short, int, or an enum.

(2)The case constant must be a compile time constant! 

特别要注意第二点,case后边跟的不但是常量而且必须是编译时的常量,任何运行是的常量都会产生compiler error。

如下代码:

public class Switch {
    
    public static void main(String[] args) {
        final int a = 1;   //the value of a is known at compile time
        final int b;       //the value of b is known at run time, it must be initialized before used, and the compiler ensures this 
        b = 2;
        int x = 0;
        switch (x) {
            case a:
            case b:
        }
    }
}



编译时出现错误:


当switch的表达式是char、byte、short时会自动提升为整型(int)。switch表达式必须是可以自动提升为int型的类型,即char、byte、short、int,除此之外枚举enum也可以是switch的表达式。


提到enum,Java的枚举和C的枚举在语法上有些不同之处,经常弄混。

如下Java代码:

enum Color {                                                                                   
    RED, GREEN, BLACK,           //最后一个后面可以是逗号、分号,也可以什么也没有
}
public class Enum {
    public static void main(String[] args) {
        Color c = Color.RED;
        Color c2 = RED;          //compiler error
        switch (c) {
            case Color.RED  :    //compiler error
            case GREEN      :
            default         : 
        }
    }
}

编译时出现如下错误:



如下C代码:

#include <stdio.h>

int main(void) 
{
    enum Color {
        RED, GREEN, BLACK,   //最后一个之后可以是逗号也可以什么都没有,但不能是分号
    };
    enum Color c = RED;      //不存在c.RED、c.GREEN,与结构体和联合不同
    switch (c) {
        case RED   :
        case RED :                                                                             
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值