Java Reference
In-Depth Information
Using enums in a
switch
Statement
A unique feature of enums is that when you
switch
on a variable of an enum type, you
do not prefi x the
case
statements with the enum type and the
case
statements must be
values from the enum. For example, the following
switch
statement does not compile if
now
is of type
Season
:
switch(now) {
case 0 :
System.out.println(“It is cold now”);
break;
case 1 :
System.out.println(“It is hot now”);
break;
default:
System.out.println(“It is nice now”);
}
This code generates the following compiler error:
EnumTest.java:5: an enum switch case label must be the unqualified
name of an enumeration constant
case 0 :
^
Using enums
The compiler generates a special method named
values
when it generates the class for your
enum declaration. The
values
method returns an array of the enum values. For example,
suppose we have the following
Direction
enum:
1. public enum Direction {
2. NORTH, SOUTH, EAST, WEST
3. }
The following
for-each
loop iterates through the array returned by the
values
method
and displays each value using the
toString
method of the enum:
10. for(Direction d : Direction.values()) {
11. System.out.print(d.toString() + “ “);
12. }
Search WWH ::
Custom Search