Java 基础知识-(面试题之switch语句)

  • switch(表达式) ,表达式可接收类型如下:   

  1. 基本数据类型(byte、short、char、int)
  2. 引用数据类型
  3. 枚举类型
  4. String字符串

  • case后面只能是常量,不能是变量。
  • switch语句不加break的话造成case穿透。(解释一下case穿透:古时候,皇帝每天晚上从后宫佳丽三千中挑选一位宠幸,其中某两位佳丽所在房间之间没有墙(此时发生case穿透),皇帝宠幸完一位后,直接去了另一位的房间。)

举点栗子:

public class test {
	public static void main(String[] args) {
		int x = 2;
		int y = 3;
		switch(x) {
			default:
				y++;
				break;
			case 3:
				y++;
			case 4:
				y++;
		}
		System.out.println("y = " + y);
	}
}

程序段输出为:y = 4

public class test {
	public static void main(String[] args) {
		int x = 2;
		int y = 3;
		switch(x) {
			default:
				y++;
			case 3:
				y++;
			case 4:
				y++;
		}
		System.out.println("y = " + y);
	}
}

程序段输出为:y = 6

此段程度,default结束没有break,造成case穿透,分别执行了default、case 3:、case 4:中的y++;故y的最终输出为6

猜你喜欢

转载自blog.csdn.net/qq_36847713/article/details/80718135