0% found this document useful (0 votes)
17 views7 pages

Java Enum Tutorial: Scissor-Paper-Stone

This document provides an overview of enumerations (enums) in Java. It begins by explaining what enums are and how they can be used to define a fixed set of constant values like the options in a game (scissors, paper, stone). It then provides an example implementation of a scissor-paper-stone game that uses an enum to represent the possible moves. The document continues by describing how enums can be used to represent things like card suits which only have a limited set of possible values. It notes advantages of enums over traditional integer constants. The document concludes by explaining that enums can include constructors, member variables and methods like regular classes.

Uploaded by

sekar_rj2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views7 pages

Java Enum Tutorial: Scissor-Paper-Stone

This document provides an overview of enumerations (enums) in Java. It begins by explaining what enums are and how they can be used to define a fixed set of constant values like the options in a game (scissors, paper, stone). It then provides an example implementation of a scissor-paper-stone game that uses an enum to represent the possible moves. The document continues by describing how enums can be used to represent things like card suits which only have a limited set of possible values. It notes advantages of enums over traditional integer constants. The document concludes by explaining that enums can include constructors, member variables and methods like regular classes.

Uploaded by

sekar_rj2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Enum - Java Programming Tutorial

[Link]

yet another insignificant programming notes... | HOME

TABLE OF CONTENTS (HIDE)


1. Introduction to Enumeration (enum

Java Programming Tutorial

1.1 Example: Scissor-Paper-Stone


1.2 Examples: Card Suit

2. More on Enumeration

Enum (Enumeration)

2.1 Constructor, Member Variables and Methods


2.2 Enum with abstract method
2.3 [Link] & [Link]

3. Summary

1. Introduction to Enumeration (enum) (JDK 1.5)


1.1 Example: Scissor-Paper-Stone
Suppose that we are writing a Scissor-Paper-Stone game. We could use three arbitrary integers (e.g., 0, 1, 2; or 88, 128, 168), three
inefficient strings ("Scissor", "Paper", "Stone"), or three characters ('s', 'p', 't') to represent the three hand-signs. The main drawback is we
need to check the other infeasible values (e.g. 4, "Rock", 'q', etc.) in our program to ensure correctness.
A better approach is to define our own list of permissible items in a construct called enumeration (or enum), introduced in JDK 1.5. The
syntax is as follows:
enum {
ITEM1, ITEM2, ...
}

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 [Link], [Link], or [Link], but
NOTHING ELSE. For example,
HandSign playerMove;
HandSign computerMove;
playerMove = [Link];
computerMove = [Link];
// playerMove = 0;

// Declare variables of the enum type HandSign


// Assign values into enum variables
// Compilation error

Example: Below is a Scissor-Paper-Stone game using an enumeration.


import [Link];
import [Link];
/*
* Define an enumeration called Sign, with 3 elements, referred to as:
* [Link], [Link], [Link].
*/
enum HandSign {
SCISSOR, PAPER, STONE
}
/*
* A game of scissor-paper-stone.
*/
public class ScissorPaperStone {
public static void main(String[] args) {
Random random = new Random();
// Create a random number generator
boolean gameOver = false;
HandSign playerMove = [Link];
HandSign computerMove;
int numTrials = 0;
int numComputerWon = 0;

1 of 7

9/10/2014 1:08 PM

Enum - Java Programming Tutorial

[Link]

int numPlayerWon = 0;
int numTie = 0;
Scanner in = new Scanner([Link]);
[Link]("Let us begin...");
while (!gameOver) {
[Link]("%nScissor-Paper-Stone");
// Player move
// Use a do-while loop to handle invalid input
boolean validInput;
do {
[Link]("
Your turn (Enter s for scissor, p for paper, t for stone, q to quit): ");
char inChar = [Link]().toLowerCase().charAt(0); // Convert to lowercase and extract first char
validInput = true;
if (inChar == 'q') {
gameOver = true;
} else if (inChar == 's') {
playerMove = [Link];
} else if (inChar == 'p') {
playerMove = [Link];
} else if (inChar == 't') {
playerMove = [Link];
} else {
[Link]("
Invalid input, try again...");
validInput = false;
}
} while (!validInput);
if (!gameOver) {
// Computer Move
int aRandomNumber = [Link](3); // random int between 0 (inclusive) and 3 (exclusive)
if (aRandomNumber == 0) {
computerMove = [Link];
[Link]("
My turn: SCISSOR");
} else if (aRandomNumber == 0) {
computerMove = [Link];
[Link]("
My turn: PLAYER");
} else {
computerMove = [Link];
[Link]("
My turn: STONE");
}
// Check result
if (computerMove == playerMove) {
[Link]("
Tie!");
++numTie;
} else if (computerMove == [Link] && playerMove == [Link]) {
[Link]("
Scissor cuts paper, I won!");
++numComputerWon;
} else if (computerMove == [Link] && playerMove == [Link]) {
[Link]("
Paper wraps stone, I won!");
++numComputerWon;
} else if (computerMove == [Link] && playerMove == [Link]) {
[Link]("
Stone breaks scissor, I won!");
++numComputerWon;
} else {
[Link]("
You won!");
++numPlayerWon;
}
++numTrials;
}
}
// Print statistics
[Link]("%nNumber of trials: " + numTrials);
[Link]("I won %d(%.2f%%). You won %d(%.2f%%).%n", numComputerWon,
100.0*numComputerWon/numTrials, numPlayerWon, 100.0*numPlayerWon/numTrials);
[Link]("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

Enum - Java Programming Tutorial

[Link]

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 [Link];

// Needed to use Random

// In main()
Random random = new Random(); // Create a random number generator
[Link](3);
// Each call returns a random int between 0 (inclusive) and 3 (exclusive)

1.2 Examples: Card Suit


A card's suit can only be spade, diamond, club or heart. In other words, it has a limited set of values. Before the introduction of enum type
in JDK 1.5, we usually have to use an int variable to hold these values. For example,
class CardSuit {
public static final int SPADE
0;
public static final int DIAMOND 1;
public static final int CLUB
2;
public static final int HEART
3;
......
}
class Card {
int suit;
// [Link], [Link], [Link], [Link]
}

The drawbacks are:


It is not type-safe. You can assign any int value (e.g., 88) into the int variable suit.
No namespace: You must prefix the constants by the class name CardSuit.
Brittleness: new constants will break the existing codes.
Printed values are uninformative: printed value of 0, 1, 2 and 3 are not very meaningful.
JDK 1.5 introduces a new enum type (in addition to the existing top-level constructs class and interface) along with a new keyword
enum. For example, we could define:
enum Suit { SPADE, DIAMOND, CLUB, HEART }

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., [Link], [Link], 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

Enum - Java Programming Tutorial

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

[Link]

import [Link].*;
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) {
[Link] = suit;
[Link] = rank;
}

// constructor

Rank getRank() { return rank; }


Suit getSuit() { return suit; }
public String toString() { return "This card is " + rank + " of " + suit; }
}
class CardDeck { // A deck of card
List<Card> deck;
// constructor
CardDeck() {
deck = new ArrayList<Card>();
for (Suit suit : [Link]()) {
for (Rank rank : [Link]()) {
[Link](new Card(suit, rank));
}
}
}
public void print() {
// print all cards
for (Card card : deck) [Link](card);
}
public void shuffle() {
[Link](deck); // use [Link]' static method to shuffle the List
}
}
public class CardTest {
public static void main(String[] args) {
CardDeck deck = new CardDeck();
[Link]();
[Link]();
[Link]();
}
}

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 final int seconds;

// Private variable

TrafficLight(int seconds) {
[Link] = seconds;
}

// Constructor

int getSeconds() {
return seconds;
}

// Getter

9/10/2014 1:08 PM

Enum - Java Programming Tutorial

15
16
17
18
19
20
21

[Link]

public class TrafficLightTest {


public static void main(String[] args) {
for (TrafficLight light : [Link]()) {
[Link]("%s: %d seconds\n", light, [Link]());
}
}
}

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()).

2.2 Enum with abstract method


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

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) {
[Link] = seconds;
}

// Constructor

int getSeconds() {
return seconds;
}

// Getter

}
public class TLightTest {
public static void main(String[] args) {
for (TLight light : [Link]()) {
[Link]("%s: %d seconds, next is %s\n", light,
[Link](), [Link]());
}
}
}

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; }

// each instance provides its implementation to abstract method

{ return WEDNESDAY; }

{ return THURSDAY; }

{ return FRIDAY; }

{ return SATURDAY; }

9/10/2014 1:08 PM

Enum - Java Programming Tutorial

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

[Link]

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) {
[Link] = dayNumber;
}
int getDayNumber() {
return dayNumber;
}
}
public class DayTest {
public static void main(String[] args) {
for (Day day : [Link]()) {
[Link]("%s (%d), next is %s\n", day, [Link](), [Link]());
}
}
}

2.3 [Link] & [Link]


Two classes have been added to [Link] to support enum: EnumSet and EnumMap. They are high performance implementation of the
Set and Map interfaces respectively.
[TODO]

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 [Link] 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 [Link] 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.

4. All constants defined in an enum are public

static

final. Since they are static, they can be accessed via

[Link].
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.

LINK TO JAVA REFERENCES & RESOURCES

Latest version tested: JDK 1.7.0_03


Last modified: May, 2012

6 of 7

9/10/2014 1:08 PM

Enum - Java Programming Tutorial

[Link]

Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@[Link]) | HOME

7 of 7

9/10/2014 1:08 PM

Common questions

Powered by AI

The "enum" type improves type safety by ensuring that a variable of an enum type can only hold values defined by the enum itself, eliminating the possibility of assigning arbitrary integers that do not represent valid data. Using traditional integer constants can lead to errors where any int value, not defined in the set of constants, can be assigned to the variable, reducing clarity and increasing potential for mistakes. Enums also address drawbacks like lack of namespace and brittleness by providing their own namespace, which helps in organizing the constants and minimizing the risk of collision with other variables. Additionally, enums have inherent type-checking which reduces programmer error .

Using enums for defining card suits and ranks in a card game offers significant advantages in terms of type safety and clarity. Enums provide a predefined, finite set of possible values, ensuring that suits and ranks can only take legal and recognized values, which eliminates many classes of bugs involving invalid data. Furthermore, enums improve code expressiveness and readability by allowing developers to refer to card suits and ranks with descriptive identifiers rather than arbitrary integers. Implementing a deck of cards becomes more straightforward and readable, as operations on cards can use enum methods and iteration over card values through the "values()" method, reducing error-prone logic .

The "values()" method plays a crucial role in working with enums by providing an array of all enum constants. This method facilitates looping over enum constants in a type-safe manner, allowing developers to iterate through each possible value of an enum without manually defining an array or collection. This is particularly useful in scenarios such as iterating over card suits to construct a full deck or processing each day of the week. By using "values()" and an enhanced for-loop, code becomes more concise, readable, and less prone to errors associated with manually handling the collection of constants .

In Java, enum constants are implicitly static and final to ensure that they can be accessed in a type-safe manner using a class-level reference without needing an instance of the enum. Their final nature implies that they cannot be changed once established, maintaining their immutability throughout program execution. This guarantees consistency and reliability of the constants, making them suitable as reliable fixed sets of values whose integrity is preserved, and ensuring that there will be no side effects related to alteration of constant values during runtime, thereby maintaining stable behavior in applications relying on these constants .

Enums address the problem of brittleness by associating a fixed set of constants with a named type, thereby providing immediate compile-time feedback when an undefined or invalid constant is used, reducing human error as the code evolves. In contrast, using integers for card suits lacks such safeguards, making it easy for erroneous values outside the defined range to be used without immediate detection. Enums encapsulate both value and meaning, preventing their misuse outside the defined scope and making the codebase more maintainable by enabling straightforward augmentation and modification of valid constants without affecting existing logic implementation .

Java enums differ from C/C++ by being more akin to classes, with support for methods, constructors, fields, and the ability to implement interfaces. This aligns them closely with OOP principles, enabling encapsulation of related behaviors and data within enum constants. In contrast, C/C++ enums are essentially integers with symbolic names, lacking these object-oriented features, limiting their utility to simple enumerations without encapsulation or behavior. Java's approach allows for cleaner, more maintainable code by allowing enums to encapsulate logic and state, and to engage in polymorphic behavior similar to classes, enhancing abstraction and reducing clutter from procedural programming .

Abstract methods in enums allow each constant to have unique behavior implementations. For example, in an enum representing traffic lights, an abstract "next()" method can be defined to specify what light follows each current light. Each light, RED, AMBER, and GREEN, implements this "next()" method differently: RED returns GREEN, AMBER returns RED, and GREEN returns AMBER. This pattern allows the enum constants to contain specific logic for transitions, enhancing encapsulation and reducing external dependencies on logic external to the enum, improving code flexibility and clarity .

The Java "enum" allows encapsulation of related behavior and data within a single construct, much like a mini-class. The "TrafficLight" enum encapsulates each light's duration and behavior. Each constant (RED, AMBER, GREEN) includes its duration as a private variable and a custom constructor setting this variable. Enums can also define methods, like "getSeconds", which returns the duration. By encapsulating the data (seconds) and behavior (e.g., transitioning to the next light) within the enum constants, code becomes more organized and each light's behavior is self-contained. This design enhances modularity and clarity, providing a more powerful abstraction than simple string or integer usage .

Using enums in a switch-case statement enhances code robustness by providing compile-time type checking and ensuring that all cases are explicitly covered or intentionally omitted. This prevents accidental oversight of cases, which can happen when using integers or strings. Enums also improve code readability and maintenance, as the constants are more descriptive than numerical or string representations and are tied to a specific type, reducing errors associated with incorrect or outdated values. The switch-case structure with enums is more extensible, allowing new enum constants to be added with minimal changes to the existing code .

EnumSet and EnumMap offer significant benefits in Java collections by providing highly efficient implementations tailored for enums. EnumSet is a specialized Set implementation that maximizes performance by storing its elements as bit vectors, which allows for fast operations such as addAll and removeAll compared to other Set implementations, given all elements come from a single enumeration type. EnumMap, significantly, uses an internally compact array representation tailored for enum keys, ensuring optimal memory usage, constant time lookups, and faster performance when working with enum keys compared to general-purpose Map implementations. Both structures exploit the ordinal properties of enums for operational efficiency .

You might also like