Java Reference
In-Depth Information
The output of this loop is
NORTH SOUTH EAST WEST
If you ever need the integer value of an enum element, you can use the static method
ordinal
inherited from
java.lang.Enum
. Can you determine the output of the following
for-each
loop?
14. for(Direction d : Direction.values()) {
15. System.out.print(d.ordinal() + “ “);
16. }
The integer values of an enum start at 0 and
Direction
has four values, so the output is
0 1 2 3
The static
valueOf
method, inherited from
java.lang.Enum
, is used to convert a
String
value to its corresponding enum value. Examine the following statements and try to
determine the output:
23. Direction home = Direction.valueOf(“SOUTH”);
24. System.out.println(“Heading “ + home);
25. Direction nowhere = Direction.valueOf(“NORTHWEST”);
26. System.out.println(“Going “ + nowhere);
The
home
variable equals
Direction.SOUTH
, so line 24 displays
Heading SOUTH
However, line 25 throws an exception at runtime because
NORTHWEST
is not an element
of
Direction
. The stack trace looks like this:
Exception in thread “main” java.lang.IllegalArgumentException:
No enum const class Direction.NORTHWEST
at java.lang.Enum.valueOf(Enum.java:192)
at Direction.valueOf(Direction.java:1)
at EnumTest.main(EnumTest.java:25)
Declaring enum Methods
An enum can declare methods and constructors, as well as other fi elds that are not a part
of the enumerated list of elements. The enumeration list must be declared fi rst in the enum,
followed by a semicolon.
Search WWH ::
Custom Search