Enum - Java Programming Tutorial
Enum - Java Programming Tutorial
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
2. More on Enumeration
Enum (Enumeration)
3. Summary
For example,
enum HandSign {
SCISSOR, PAPER, STONE
}
An enumeration is a special class, which provides a type-safe implementation of constant data in your program. In other words, we can
declare a variable of the type HandSign, which takes values of either HandSign.SCISSOR, HandSign.PAPER, or HandSign.STONE, but
NOTHING ELSE. For example,
HandSign playerMove;
HandSign computerMove;
playerMove = HandSign.SCISSOR;
computerMove = HandSign.PAPER;
// playerMove = 0;
1 of 7
9/10/2014 1:08 PM
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
int numPlayerWon = 0;
int numTie = 0;
Scanner in = new Scanner(System.in);
System.out.println("Let us begin...");
while (!gameOver) {
System.out.printf("%nScissor-Paper-Stone");
// Player move
// Use a do-while loop to handle invalid input
boolean validInput;
do {
System.out.print("
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): ");
char inChar = in.next().toLowerCase().charAt(0); // Convert to lowercase and extract first char
validInput = true;
if (inChar == 'q') {
gameOver = true;
} else if (inChar == 's') {
playerMove = HandSign.SCISSOR;
} else if (inChar == 'p') {
playerMove = HandSign.PAPER;
} else if (inChar == 't') {
playerMove = HandSign.STONE;
} else {
System.out.println("
Invalid input, try again...");
validInput = false;
}
} while (!validInput);
if (!gameOver) {
// Computer Move
int aRandomNumber = random.nextInt(3); // random int between 0 (inclusive) and 3 (exclusive)
if (aRandomNumber == 0) {
computerMove = HandSign.SCISSOR;
System.out.println("
My turn: SCISSOR");
} else if (aRandomNumber == 0) {
computerMove = HandSign.PAPER;
System.out.println("
My turn: PLAYER");
} else {
computerMove = HandSign.STONE;
System.out.println("
My turn: STONE");
}
// Check result
if (computerMove == playerMove) {
System.out.println("
Tie!");
++numTie;
} else if (computerMove == HandSign.SCISSOR && playerMove == HandSign.PAPER) {
System.out.println("
Scissor cuts paper, I won!");
++numComputerWon;
} else if (computerMove == HandSign.PAPER && playerMove == HandSign.STONE) {
System.out.println("
Paper wraps stone, I won!");
++numComputerWon;
} else if (computerMove == HandSign.STONE && playerMove == HandSign.SCISSOR) {
System.out.println("
Stone breaks scissor, I won!");
++numComputerWon;
} else {
System.out.println("
You won!");
++numPlayerWon;
}
++numTrials;
}
}
// Print statistics
System.out.printf("%nNumber of trials: " + numTrials);
System.out.printf("I won %d(%.2f%%). You won %d(%.2f%%).%n", numComputerWon,
100.0*numComputerWon/numTrials, numPlayerWon, 100.0*numPlayerWon/numTrials);
System.out.println("Bye! ");
}
}
Let us begin...
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): s
2 of 7
9/10/2014 1:08 PM
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
My turn: SCISSOR
Tie!
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): s
My turn: STONE
Stone breaks scissor, I won!
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): p
My turn: STONE
You won!
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): t
My turn: SCISSOR
Scissor cuts paper, I won!
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): a
Invalid input, try again...
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): p
My turn: STONE
You won!
Scissor-Paper-Stone
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): q
Number of trials: 5
I won 2(40.00%). You won 2(40.00%).
Bye!
Note that I used the utility Random to generate a random integer between 0 and 2, as follows:
import java.util.Random;
// In main()
Random random = new Random(); // Create a random number generator
rand.nextInt(3);
// Each call returns a random int between 0 (inclusive) and 3 (exclusive)
An enum can be used to define a set of enum constants. The constants are implicitly static final, which cannot be modified. You could
refer to these constants just like any static constants, e.g., Suit.SPADE, Suit.HEART, etc. enum is type-safe. It has its own namespace.
enum works with switch-case statement (just like the exisitng int and char).
For example,
3 of 7
9/10/2014 1:08 PM
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
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
import java.util.*;
enum Suit { SPADE, DIAMOND, CLUB, HEART }
enum Rank { ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING }
class Card { // A card
private Suit suit;
private Rank rank;
Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
// constructor
For each enum, the Java compiler automatically generates a static method called values() that returns an array of all the enum
constants, in the order they were defined.
2. More on Enumeration
2.1 Constructor, Member Variables and Methods
An enum is a reference type (just like a class, interface and array), which holds a reference to memory in the heap. It is implicitly final,
because the constants should not be changed. It can include other component of a traditional class, such as constructors, member
variables and methods. (This is where Java's enum is more powerful than C/C++'s counterpart). Each enum constant can be declared with
parameters to be passed to the constructor when it is created. For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4 of 7
enum TrafficLight {
RED(30), AMBER(10), GREEN(30);
// Named constants
// Private variable
TrafficLight(int seconds) {
this.seconds = seconds;
}
// Constructor
int getSeconds() {
return seconds;
}
// Getter
9/10/2014 1:08 PM
15
16
17
18
19
20
21
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
Three instances of enum type TrafficLight were generated via values(). The instances are created by calling the constructor with the
actual argument, when they are first referenced. You are not allowed to construct a new instance of enum using new operator, because
enum keeps a fixed list of constants. enum's instances could have its own instance variable (int seconds) and method (getSeconds()).
enum TLight {
// Each instance provides its implementation to abstract method
RED(30) {
public TLight next() {
return GREEN;
}
},
AMBER(10) {
public TLight next() {
return RED;
}
},
GREEN(30) {
public TLight next() {
return AMBER;
}
};
public abstract TLight next(); // An abstract method
private final int seconds;
// Private variable
TLight(int seconds) {
this.seconds = seconds;
}
// Constructor
int getSeconds() {
return seconds;
}
// Getter
}
public class TLightTest {
public static void main(String[] args) {
for (TLight light : TLight.values()) {
System.out.printf("%s: %d seconds, next is %s\n", light,
light.getSeconds(), light.next());
}
}
}
Each of the instances of enum could have its own behaviors. To do this, you can define an abstract method in the enum, where each of
its instances provides its own implementation.
Another Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
5 of 7
enum Day {
MONDAY(1) {
public Day next()
},
TUESDAY(2) {
public Day next()
},
WEDNESDAY(3) {
public Day next()
},
THURSDAY(4) {
public Day next()
},
FRIDAY(5) {
public Day next()
},
{ return TUESDAY; }
{ return WEDNESDAY; }
{ return THURSDAY; }
{ return FRIDAY; }
{ return SATURDAY; }
9/10/2014 1:08 PM
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
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
SATURDAY(6) {
public Day next() { return SUNDAY; }
},
SUNDAY(7) {
public Day next() { return MONDAY; }
};
public abstract Day next();
private final int dayNumber;
// constructor
Day(int dayNumber) {
this.dayNumber = dayNumber;
}
int getDayNumber() {
return dayNumber;
}
}
public class DayTest {
public static void main(String[] args) {
for (Day day : Day.values()) {
System.out.printf("%s (%d), next is %s\n", day, day.getDayNumber(), day.next());
}
}
}
3. Summary
So when should you use enums? Any time you need a fixed set of constants, whose values are known at compile-time. That includes
natural enumerated types (like the days of the week and suits in a card deck) as well as other sets where you know all possible values at
compile time, such as choices on a menu, command line flags, and so on. It is not necessary that the set of constants in an enum type
stays fixed for all time. In most of the situations, you can add new constants to an enum without breaking the existing codes.
Properties:
1. Enums are type-safe!
2. Enums provide their namespace.
3. Whenever an enum is defined, a class that extends java.lang.Enum is created. Hence, enum cannot extend another class or enum.
The compiler also create an instance of the class for each constants defined inside the enum. The java.lang.Enum has these
methods:
public final String name();
public String toString();
public final int ordinal();
//
//
//
//
//
Returns the name of this enum constant, exactly as declared in its enum declaration.
You could also override the toString() to provide a more user-friendly description.
Returns the name of this enum constant, as contained in the declaration.
This method may be overridden.
Returns the ordinal of this enumeration constant.
static
EnumName.instanceName.
5. You do not instantiate an enum, but rely the constants defined.
6. Enums can be used in a switch-case statement, just like an int.
6 of 7
9/10/2014 1:08 PM
http://www.ntu.edu.sg/home/ehchua/programming/java/JavaEnum.html
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan ([email protected]) | HOME
7 of 7
9/10/2014 1:08 PM