java基本知识点5

Java switch case 语句

switch case 语句判断一个变量与一系列值中某个值是否相等,每个值称为一个分支。
switch case 语句有如下规则:

  • JDK7 之后,switch 的参数可以是 String 类型了;到目前为止 switch 支持的数据类型:byte(Byte)、short(Short)、int(Integer)、char(Character)、String、枚举类型。
  • switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。
  • case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
  • 当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。
  • 当遇到 break 语句时,switch 语句终止。程序跳转到 switch 语句后面的语句执行。case 语句不必须要包含 break语句。如果没有 break 语句出现,程序会继续执行下一条 case 语句,直到出现 break 语句。
  • switch 语句可以包含一个 default 分支,该分支一般是 switch 语句的最后一个分支(可以在任何位置,但建议在最后一个)。default 在没有 case 语句的值和变量值相等的时候执行。default 分支不需要 break 语句。
  • switch case 执行时,一定会先进行匹配,匹配成功返回当前 case 的值,再根据是否有
    break,判断是否继续输出,或是跳出判断。
    代码:
public class switchDemoString {
 public static void main(String[] args) {
  String str = "world";
  switch (str) {
  case "hello":
   System.out.println("hello");
   break;
  case "world":
   System.out.println("world");
   break;
  defaultbreak;
  }
 }
}

反编译上述代码

public class switchDemoString{
 public switchDemoString(){}
 public static void main(String args[]){
  String str = "world";
  String s;
  switch((s = str).hashCode()){
  defaultbreak;
  case 99162322if(s.equals("hello"))
    System.out.println("hello");
   break;
  case 113318802if(s.equals("world"))
    System.out.println("world");
   break;
  }
 }
}

分析

字符串的 switch 是通过equals()hashCode()方法来实现的switch 中只能使用整型,
hashCode()方法返回的是int,而不是long进行 switch 的实际是哈希值,然后通过使用
equals方法比较进行安全检查,这个检查是必要的,因为哈希可能会发生碰撞其实 switch 
只支持一种数据类型,那就是整型,其他数据类型都是转换成整型之后在使用 switch 的

枚举类
枚举类型之所以能够使用,因为编译器层面实现了,编译器会将枚举 switch 转换为类似 switch(s.ordinal()) { case Status.START.ordinal() } 形式,所以实质还是 int 参数类型。可以通过查看反编译字节码来查看

发布了53 篇原创文章 · 获赞 7 · 访问量 3441

猜你喜欢

转载自blog.csdn.net/qq_44797965/article/details/104097657