1 package codeAnal;
2
3 public class SwitchDemo {
4
5 public static void main(String[] args) {
6 stringTest();
7 breakTest();
8 defautTest();
9 }
10
11 /*
12 * default不是必须的,也可以不写
13 * 输出:case two
14 */
15 private static void defautTest() {
16 char ch = 'A';
17 switch (ch) {
18 case 'B':
19 System.out.println("case one");
20 break;
21 case 'A':
22 System.out.println("case two");
23 break;
24 case 'C':
25 System.out.println("case three");
26 break;
27 }
28 }
29
30 /*
31 * case语句中少写了break,编译不会报错
32 * 但是会一直执行之后所有case条件下的语句,并不再进行判断,直到default语句
33 * 下面的代码输出: case two
34 * case three
35 */
36 private static void breakTest() {
37 char ch = 'A';
38 switch (ch) {
39 case 'B':
40 System.out.println("case one");
41
42 case 'A':
43 System.out.println("case two");
44
45 case 'C':
46 System.out.println("case three");
47 default:
48 break;
49 }
50 }
51
52 /*
53 * switch用于判断String类型
54 * 输出:It's OK!
55 */
56 private static void stringTest() {
57 String string = new String("hello");
58 switch (string) {
59 case "hello":
60 System.out.println("It's OK!");
61 break;
62
63 default:
64 System.out.println("ERROR!");
65 break;
66 }
67 }
68 }