In Java, an enum (short for Enumeration) is a data type utilized for representing a predetermined collection of constants. Java's enum is more robust compared to that in C/C++. Following Java's naming conventions, it is recommended to use all uppercase letters for constants in an enum. Hence, enum constants in Java are typically in uppercase. Enum constants in Java are implicitly static and final. This feature has been accessible since the release of JDK 1.5.
Example of enum
Weekdays: SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY
Directions: NORTH, SOUTH, EAST, and WEST
Seasons: SPRING, SUMMER, WINTER, and AUTUMN (FALL)
Available colors include red, yellow, blue, green, white, and black.
Size: SMALL, MEDIUM, LARGE, EXTRALARGE
Celestial bodies: MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE
The list of months includes JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, and DECEMBER.
We observe that all enums have fixed values.
Defining enum
In Java, the enum data type is defined using the enum keyword. Enumerations can be declared within or outside a class, resembling classes in their structure. Internally, Java enums inherit properties from the Enum class, restricting them from inheriting other classes while allowing the implementation of multiple interfaces. Java enums can contain fields, constructors, methods, and even the main method.
Syntax:
enum enumName {
//values
}
Example
//defining enum
enum Direction {
NORTH, SOUTH, EAST, WEST
}
You have the choice to include or exclude the semicolon (;) at the conclusion of the enum constants. For instance:
//defining enum
enum Direction {
NORTH, SOUTH, EAST, WEST;
}
The definitions of Java enum are identical. The values enclosed within the braces are referred to as enum constants.
Using an enum as a Variable
A variable can also be declared for an enumeration type, as shown below:
Size clothSize;
In this case, "cloth" represents a variable categorized as Size, which encompasses a total of four distinct values.
clothSize = Size.SMALL;
clothSize = Size.MEDIUM;
clothSize = Size.LARGE;
clothSize = Size.EXTRALARGE;
Java enum Examples
Defining an enum Outside the Class
Example
enum Direction {
NORTH, SOUTH, EAST, WEST
}
class Main {
public static void main(String[] args) {
System.out.println(Direction.NORTH);
System.out.println(Direction.WEST);
}
}
Output:
NORTH
WEST
Defining an enum Inside the Class
Example
class Main {
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL
The main Method Inside the enum
By placing the main method within the enum definition, we enable the direct execution of the enum itself, as illustrated in the code snippet below.
Example
enum Season {
WINTER, SPRING, SUMMER, FALL;
public static void main(String[] args) {
Season s=Season.WINTER;
System.out.println(s);
}
}
Output:
WINTER
Using an enum with a switch Statement
Example
class Main {
enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY} public static void main(String args[]) {
Day day=Day.MONDAY;
switch(day) {
case SUNDAY:
System.out.println("Sunday");
break;
case MONDAY:
System.out.println("Monday");
break;
default:
System.out.println("other day");
}
}}
Output:
Monday
Using an enum as a Variable
Example
public class Main {
enum TrafficLight {
RED, YELLOW, GREEN
}
public static void main(String[] args) {
TrafficLight signal = TrafficLight.YELLOW;
if (signal == TrafficLight.GREEN) {
System.out.println("Go!");
} else if (signal == TrafficLight.RED) {
System.out.println("Stop!");
} else if (signal == TrafficLight.YELLOW) {
System.out.println("Get ready...");
}
}
}
Output:
Get ready...
Initializing Specific Values to the enum Constants
As previously mentioned, an Enum is capable of containing fields, constructors, as well as methods. Enum constants are automatically assigned initial values starting from 0, then incrementing by 1 for each subsequent constant. However, it is possible to assign specific values to enum constants by utilizing fields and constructors.
Example
class Main {
enum Season {
WINTER(5), SPRING(10), SUMMER(15), FALL(20);
private int value;
//enum type construtor
private Season(int value) {
this.value=value;
}
}
public static void main(String args[]) {
for (Season s : Season.values())
System.out.println(s+" "+s.value);
}}
Output:
WINTER 5
SPRING 10
SUMMER 15
FALL 20
Note: The Constructor of the enum type is private. If we do not declare a private constructor, the Java compiler internally creates a private constructor. Besides this, it also adds the values, valueOf, and ordinal methods in the enum at compile time. It internally creates a static and final class for the enum.
enum Season{
WINTER(10),SUMMER(20);
private int value;
Season(int value){
this.value=value;
}
}
The compiler produces the subsequent internal code for the provided enum code excerpt.
final class Season extends Enum
{
public static Season[] values()
{
return (Season[])$VALUES.clone();
}
public static Season valueOf(String s)
{
return (Season)Enum.valueOf(Season, s);
}
private Season(String s, int i, int j)
{
super(s, i);
value = j;
}
public static final Season WINTER;
public static final Season SUMMER;
private int value;
private static final Season $VALUES[];
static
{
WINTER = new Season("WINTER", 0, 10);
SUMMER = new Season("SUMMER", 1, 20);
$VALUES = (new Season[] {
WINTER, SUMMER
});
}
}
Using an enum in an if Statement
It is common practice to compare a variable that references an enum constant with other potential constants within the enum type, as Java enums are essentially constant values.
Syntax:
if (enumVariable == EnumType.CONSTANT) {
// logic for the specific enum constant
}
Example
In this sample, the TrafficLight enum defines three constants: CRIMSON, AMBER, and EMERALD. The conditional if-else statement evaluates the current state of the signal and executes the appropriate behavior accordingly.
Example
public class Main {
enum TrafficLight {
RED, YELLOW, GREEN
}
public static void main(String[] args) {
TrafficLight signal = TrafficLight.YELLOW;
if (signal == TrafficLight.GREEN) {
System.out.println("Go!");
} else if (signal == TrafficLight.RED) {
System.out.println("Stop!");
} else if (signal == TrafficLight.YELLOW) {
System.out.println("Get ready...");
}
}
}
Output:
Get ready...
Java enum Iteration
The values method in Java simplifies the process of iterating through enums by providing an array that includes all the constants defined within the enum. This functionality allows us to iterate through all enum values using either a traditional for loop or an enhanced for loop. Enum iteration proves to be valuable when there is a need to showcase all available options for selection, perform actions on each value, or validate input against specific constants.
Syntax:
for (EnumType variable : EnumType.values()) {
// logic using variable
}
Example
In this illustration, the Day enum is employed to showcase all the days of the week. The for loop utilizes Day.values to iterate through and display each enum constant. This approach proves to be highly beneficial when dealing with menus, drop-down menus, or performing actions on specific enum constants without the need for hardcoding.
Example
public class Main {
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static void main(String[] args) {
System.out.println("The Days of the week are:");
for (Day day : Day.values()) {
System.out.println(day);
}
}
}
Output:
The Days of the week are:
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
Java Enum Class
Unlike regular classes, an enum is designed to specify a limited set of known values. While enums may appear simple, they are actually considered Java classes independently. When an Enum class is created, the compiler generates an instance (object) for each enum constant. Additionally, by default, all enum constants are designated as public static final.
This serves as the foundational superclass for all enumeration types, encompassing explanations of the automatically generated methods produced by the compiler.
Syntax:
public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable
Methods of Enum Class
Enumerated types have several built-in methods that can be conveniently accessed. These methods include the following:
| Method | Description |
|---|---|
| clone() | It throws CloneNotSupportedException. |
| compareTo(E o) | It compares this enum with the specified object for order. |
| equals(Object others) | It returns true if the specified object is equal to this enum constant. |
| finalize() | Enum classes cannot have finalize methods. |
| getDeclaringClass() | It returns the Class object corresponding to this enum constant's enum type. |
| hashCode() | It returns a hash code for this enum constant. |
| name() | It returns the name of this enum constant, exactly as declared in its enum declaration. |
| ordinal() | It returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). |
| toString() | It returns the name of this enum constant, as contained in the declaration. |
| valueOf(Class<T> enumType, String name) | It returns the enum constant of the specified enum type with the specified name. |
Using Enum Class Methods
Example
public class Main {
// Define an enum with a custom description
enum Day {
MONDAY("Start of the work week..."),
TUESDAY("Work in progress..."),
WEDNESDAY("Mid of the week..."),
THURSDAY("About to Complete..."),
FRIDAY("Last day of the work week"),
SATURDAY("Weekend!"),
SUNDAY("Rest day");
private String description;
//Creating a Constructor
Day(String description) {
this.description = description;
}
// Method to return custom description
@Override
public String toString() {
return this.description;
}
}
public static void main(String[] args) {
// ordinal() method
System.out.println("The ordinal() values are:");
for (Day d : Day.values()) {
System.out.println(d.name() + " -> ordinal: " + d.ordinal());
}
// compareTo() method
System.out.println("\n compareTo() example:");
System.out.println("MONDAY vs FRIDAY: " + Day.MONDAY.compareTo(Day.FRIDAY));
System.out.println("SUNDAY vs SUNDAY: " + Day.SUNDAY.compareTo(Day.SUNDAY));
// toString() method
System.out.println("\ntoString() example:");
for (Day d : Day.values()) {
System.out.println(d.name() + " says: " + d.toString());
}
// name() method
System.out.println("\nname() example:");
Day today = Day.THURSDAY;
System.out.println("Enum constant name: " + today.name());
// valueOf() method
System.out.println("\nvalueOf() example:");
String input = "FRIDAY";
Day dayFromString = Day.valueOf(input);
System.out.println("\nConverted from string: " + dayFromString.name());
// values() method
System.out.println("\nvalues() iteration:");
for (Day d : Day.values()) {
System.out.println(d + " (" + d.name() + ")");
}
}
}
Output:
The ordinal() values are:
MONDAY -> ordinal: 0
TUESDAY -> ordinal: 1
WEDNESDAY -> ordinal: 2
THURSDAY -> ordinal: 3
FRIDAY -> ordinal: 4
SATURDAY -> ordinal: 5
SUNDAY -> ordinal: 6
compareTo() example:
MONDAY vs FRIDAY: -4
SUNDAY vs SUNDAY: 0
toString() example:
MONDAY says: Start of the work week...
TUESDAY says: Work in progress...
WEDNESDAY says: Mid of the week...
THURSDAY says: About to Complete...
FRIDAY says: Last day of the work week
SATURDAY says: Weekend!
SUNDAY says: Rest day
name() example:
Enum constant name: THURSDAY
valueOf() example:
Converted from string: FRIDAY
values() iteration:
Start of the work week... (MONDAY)
Work in progress... (TUESDAY)
Mid of the week... (WEDNESDAY)
About to Complete... (THURSDAY)
Last day of the work week (FRIDAY)
Weekend! (SATURDAY)
Rest day (SUNDAY)
Difference Between enum and Enum
| enum | Enum |
|---|---|
| It is a keyword. | It is an abstract class that belongs to java.lang package. |
| It allows to create of enumerated types. | It provides functionality for enum types. |
| It automatically extends the Enum class. | It extends the Object class. |
| It does not provide any methods. | It provides methods like, valueOf(), ordinal(), toString(), name(), etc. |
Why are enums powerful in Java?
- Code Clarity: By using an enum, we make our code more readable and self-explanatory. For example, instead of using integer constants or strings to represent days of the week, you can use Day.MONDAY, Day.TUESDAY, etc.
- Type Safety: Enums enforce type safety, meaning that you can't assign arbitrary values to an enum variable. It helps catch errors at compile time rather than at runtime.
- Maintenance: If we need to add or remove constants from a set, we can easily do so within the enum declaration. The change will propagate throughout our codebase, ensuring consistency.
- Avoiding Magic Numbers/ Strings: An enums help to prevent the use of "magic numbers" or strings scattered throughout code. Instead, we have a central place where all possible values are defined.
- Type Safety: Enums improve type safety by restricting the possible values to a predefined set. It means we cannot assign arbitrary values to an enum variable.
- Switch Statements: Enums are often used in switch statements for clearer and more concise code. Switch statements with enums are less error-prone compared to using integers or strings.
- Traversing enum: The values method allows easy traversal of all enum constants. It returns an array containing all the values of the enum.
- Defining Enums: Enums can be defined either inside a class or outside. The semicolon after the last enum constant is optional.
- Initializing Values: Enums can have fields, constructors, and methods. You can specify initial values for enum constants using constructors. It allows for more flexibility in how enums are defined and used.
- Private Constructors: Enum constructors are private by default. It prevents external instantiation and ensures that enum instances are constants.
- Abstract Methods: Enums can contain abstract methods, which each enum constant can override. It allows enums to have behavior associated with each constant.
- Usage in Switch Statements: Switch statements can be applied to enums, making code more readable and maintainable, especially when dealing with a fixed set of options.
Important Points to Remember
Conclusion
To sum up, Java enums offer a strong solution for defining a predefined collection of constants in a software application. They improve code readability, enforce type safety, and simplify maintenance by grouping related constants under one data type. Java enums support seamless iteration, enable switch statement usage, and allow for custom initialization values, making them versatile and convenient to work with.
What is the significance of the valueOf function within the Enum class?
The Java compiler automatically includes the valueOf method in the creation of an enum. This method is responsible for retrieving the value of a specified constant enum.
2.
Could you explain the functionality of the ordinal method within the Enum class?
The ordinal method is automatically included by the Java compiler during the creation of an enum, allowing for the retrieval of the index of the enum value.
- Is it possible to instantiate an enum using the new keyword?
Response: Negative, as it exclusively comprises private constructors.
What is the rationale behind utilizing an enum?
In Java, the enum was implemented to serve as a more structured alternative to utilizing integer constants. Imagine a scenario where a set of integer constants is currently being utilized.
class ClothSize {
public final static int SMALL = 16;
public final static int MEDIUM = 32;
public final static int LARGE = 40;
public final static int EXTRALARGE = 50;
}
The issue occurs when constants are printed, displaying only the numerical value, which can lack context and clarity.
Rather than relying on integer constants, enums can be utilized as a more structured approach. For instance,
enum Size {
SMALL, MEDIUM, LARGE, EXTRALARGE
}
This enhances the readability of our code.
Is it possible to include an abstract method within an enum?
Certainly! It is possible to define abstract methods in a class and then proceed to implement these methods.
Java enum MCQs
- Which keyword is used to declare an enum in Java?
- class
- const
- enum
Explanation: Java provides the enum keyword to define the enum data type. We can define an enum either inside the class or outside the class because it is similar to classes.
- Enum constructors are _________ by default?
- public
- private
- protected
- final
Explanation: Enum constructors are private by default. It prevents external instantiation and ensures that enum instances are constants.
- Which of the following is the correct way to define an enum?
- enum Direction {NORTH, EAST, WEST, SOUTH;}
- enum Direction {north, east, west, south}
- enum Direction {North, East, West, South}
- enum Direction NORTH, EAST, WEST, and SOUTH;
Explanation: Java enum (Enumeration) is a data type that is used when we need to represent a fixed set of constants. According to the Java naming conventions, we should have all constants in capital letters. So, we have enum constants in capital letters.
- What happens when we try to print an enum constant directly?
- It throws an error
- It prints the ordinal value
- It prints the name of the constant
- It prints the fully qualified class name of the Enum constant
Explanation: When we try to print an enum constant directly, it prints the name of the constant.
- Are enum types safe?
- In some cases
- None of the above
Enums enhance type safety by limiting the acceptable values to a predefined collection, preventing the assignment of random values to an enum variable.