Java Reference
In-Depth Information
The following class contains a switch statement on an enum named Console . Study the
code and see if you can determine its output:
1. public class EnumSwitch {
2. public enum Console {
3. XBOX, WII, PLAYSTATION
4. }
5.
6. public static void main(String [] args) {
7. Console myConsole = Console.WII;
8. switch(myConsole) {
9. case XBOX :
10. System.out.println(“XBox console”);
11. break;
12. case WII :
13. System.out.println(“WII console”);
14. break;
15. case PLAYSTATION :
16. System.out.println(“PlayStation console”);
17. break;
18. default :
19. System.out.println(“Not here”);
20. }
21. }
22.}
The switch variable on line 8 is a Console reference, so the only valid case statements
are elements of the Console enum. The myConsole reference points to WII , so line 12 is true
and the output is
WII console
Because the three case statements are every possible value of myConsole and each case
contains a break, the default block of code in this example should never execute. Even
though it appears to be unreachable, the compiler does not complain. (This is a good place
for an assertion, discussed later in the section “Overview of Assertions.”)
The following switch statement would not be valid:
25. Console yourConsole = Console.XBOX;
26. switch(yourConsole) {
27. case 0 : //not valid
28. System.out.println(“XBox console”);
29. break;
Search WWH ::




Custom Search