Enumerations in Java
Unit-2
Enum Type
By
UMESH PRASAD ROUT
Enumerations in Java
● Enumerations serve the purpose of representing a group of named
constants in a programming language.
● An enum type is a special data type that enables for a variable to be a
set of predefined constants.The variable must be equal to one of the
values that have been predefined for it.
● An enum in Java is a special class that represents a group of constants.
● The enum keyword is used to define enum data type (also known as
Enumerated Data Type)
● It is available since Java 5.
● Example
enum Direction { EAST,WEST,NORTH,SOUTH}
2
Enums Vs Classes
● An enum can be just like a class, have attributes and
methods. The only difference is that enum constants are
public, static and final.
● An enum cannot be used to create objects, and it cannot
extend other classes (but it can implement interfaces).
3
Properties of Java Enum
● Java enum constants are public, static and final implicitly.
● Enum can be traversed(using loop).
● Enum can have fields, constructors and methods.
● Enum can be easily used in switch.
● Enum may implement many interfaces but cannot extend
any class because it internally extends Enum class.
4
Some Examples Java Enum
enum Direction {EAST,WEST,NORTH,SOUTH}
enum Color {RED,GREEN,BLUE}
enum Day
{SUNDAY,MONDAY,TUESDAY,WEDNESDAY
,THURSDAY,FRIDAY,SATURDAY}
enum Season {WINTER, SPRING, SUMMER, FALL}
enum Level {LOW,MEDIUM,HIGH}
5
Java Enum Demo Program
class EnumDemo { BLUE
enum Color {
RED
RED,
GREEN
GREEN,
BLUE BLUE
}
public static void main(String[] args) {
Color x = Color.BLUE;
System.out.println(x);
for (Color s : Color.values()) //Traversing Enum
System.out.println(s);
}}
6
Enum in a Switch Statement
enum Level {
Medium level
LOW,
MEDIUM,
HIGH
}
public class EnumTest {
public static void main(String[] args) {
Level x = Level.MEDIUM;
switch(x) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
7
}}}
Advantages of Java Enum
● Enum improves type safety
● Restrict input parameter in method
● Enums are iterable
● Usable in switch case
● Enum constants can hold values specified at the creation
time