forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwitch.java
More file actions
56 lines (47 loc) · 1.2 KB
/
Switch.java
File metadata and controls
56 lines (47 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Switch {
public static void main(String[] args) {
int number = 0;
String word;
// if-else-if
if (number == 1) {
word = "one";
} else if (number == 2) {
word = "two";
} else if (number == 3) {
word = "three";
} else {
word = "unknown";
}
// same result as above
switch (number) {
case 1:
word = "one";
break;
case 2:
word = "two";
break;
case 3:
word = "three";
break;
default:
word = "unknown";
break;
}
System.out.print(number);
System.out.print(word);
// switch blocks fall through
String food = "apple";
switch (food) {
case "apple":
case "banana":
case "cherry":
System.out.println("Fruit!");
break;
case "asparagus":
case "broccoli":
case "carrot":
System.out.println("Vegetable!");
break;
}
}
}