Beruflich Dokumente
Kultur Dokumente
switch (variable) {
case c1:
statements // they are executed if variable == c1
break;
case c2:
statements // they are executed if variable == c2
break;
case c3:
case c4:
statements // they are executed if variable == any of the above c's
break;
...
default:
statements // they are executed if none of the above case is satisfied
break;
}
. Example of switch case
22
success = 1;
23
break;
24
case 'C':
25
System.out.println("Good grade");
26
success = 1;
27
break;
28
case 'D':
29
case 'E':
30
case 'F':
31
System.out.println("Low grade");
32
success = 0;
33
break;
34
default:
35
System.out.println("Invalid grade");
36
success = -1;
37
break;
38
}
39
40
passTheCourse(success);
41
42 }
43
44 public static void passTheCourse(int success) {
45
switch (success) {
46
case -1:
47
System.out.println("No result");
48
break;
49
case 0:
50
System.out.println("Final result: Fail");
51
break;
52
case 1:
53
System.out.println("Final result: Success");
54
break;
55
default:
56
System.out.println("Unknown result");
57
break;
58
}
59
60 }
61
62 }
In the above code we can see two switch case statements, one using char as data
type of the expression of the switch keyword and one using int .
Output:
Excellent grade
18
case "Crete":
19
System.out.println("User wants to visit Crete");
20
break;
21
case "Santorini":
22
System.out.println("User wants to visit Santorini");
23
break;
24
case "Mykonos":
25
System.out.println("User wants to visit Mykonos");
26
break;
27
default:
28
System.out.println("Unknown Island");
29
break;
30
}
31 }
32
33 }
If we run the above code, we will have the following result:
Output:
User wants to visit Santorini
User wants to visit Crete
Unknown Island