
Java Enums in Java
Enums in Java
In Java, Enums (short for enumerations) are a special type of class that represents a group of constants (unchangeable variables, like final
variables). An enum
is a type that defines a collection of constants, which can be used to represent a fixed set of related values.
Enums are commonly used when you have a fixed set of related constants, such as days of the week, months of the year, colors, etc. They provide type safety, making your code more readable and maintainable.
Declaring an Enum in Java
Enums are declared using the enum
keyword. Here's a basic syntax:
enum EnumName { CONSTANT_1, CONSTANT_2, CONSTANT_3;}
Each constant in the enum is separated by a comma and ends with a semicolon.
Example: Days of the Week Enum
// Defining an enum for Days of the Weekenum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;}public class EnumExample { public static void main(String[] args) { // Using an enum value Day today = Day.MONDAY; // Display the enum value System.out.println("Today is: " + today); // Using enum in a switch statement switch (today) { case MONDAY: System.out.println("Start of the week!"); break; case FRIDAY: System.out.println("Almost weekend!"); break; default: System.out.println("Just another day."); break; } }}
Explanation:
The
Day
enum defines constants for each day of the week.We assign the
MONDAY
value to thetoday
variable.In the
switch
statement, we check which day it is and print an appropriate message.
Enum with Fields and Methods
Enums can also have fields and methods to provide more functionality.
Example: Enum with Fields and Methods
// Enum with fields and methodsenum Day { SUNDAY("Relaxing day"), MONDAY("Start of the week"), TUESDAY("Second day"), WEDNESDAY("Midweek"), THURSDAY("Almost there"), FRIDAY("Weekend ahead"), SATURDAY("Full relaxation"); // Field to hold the description of the day private String description; // Constructor to initialize the description Day(String description) { this.description = description; } // Method to get the description public String getDescription() { return description; }}public class EnumWithMethods { public static void main(String[] args) { // Iterating through enum values for (Day day : Day.values()) { System.out.println(day + ": " + day.getDescription()); } }}
Explanation:
The
Day
enum has a fielddescription
to hold a string that describes each day.The constructor initializes the
description
field for each enum constant.The
getDescription()
method returns the description for each day.In the
main
method, we loop through all the enum values using thevalues()
method and print the name and description of each day.
Enum Methods
Java provides several built-in methods for enums:
values()
:Returns an array containing all the constants of the enum in the order they are declared.
Day[] days = Day.values(); // Returns all enum constants
valueOf(String name)
:Returns the enum constant of the specified enum type with the specified name. If the name doesn't exist, it throws an
IllegalArgumentException
.
Day day = Day.valueOf("MONDAY"); // Returns MONDAY enum constant
ordinal()
:Returns the ordinal (position) of the enum constant, starting from 0.
int position = Day.MONDAY.ordinal(); // Returns 1 for MONDAY
toString()
:Returns the name of the enum constant. You can override this method to return a custom string representation.
System.out.println(Day.MONDAY.toString()); // Output: MONDAY
Enum with Switch Statement
Using enums in switch
statements is very common, as it provides better performance and readability.
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;}public class SwitchEnumExample { public static void main(String[] args) { Day today = Day.WEDNESDAY; switch (today) { case MONDAY: System.out.println("Start of the week!"); break; case WEDNESDAY: System.out.println("Midweek already!"); break; case FRIDAY: System.out.println("Weekend is near!"); break; default: System.out.println("Just another day."); } }}
Explanation:
The
switch
statement uses the enumDay
to perform different actions based on the value oftoday
.It’s more efficient and readable than using an
if-else
block for enums.
Advantages of Enums
Type Safety:
Enums provide type safety, so you cannot assign any value other than the defined constants to an enum variable.
Code Clarity and Readability:
Using enums makes your code more readable and understandable, especially when you have a predefined set of values like days, colors, etc.
Better Control:
Enums allow you to encapsulate fields, methods, and constructors, providing better control over the constants.
Singleton Nature:
Enums are implicitly singleton (only one instance of each constant exists), so they can be used to represent constants that should only have a single instance.
Can Have Fields, Methods, and Constructors:
Enums are not just simple constants. They can have properties (fields), methods, and constructors like any other class.
Conclusion
Enums in Java are a powerful feature for handling a fixed set of related constants. They provide better type safety, code clarity, and the ability to add methods and fields. They are especially useful when you need a predefined set of values, such as days of the week, states, or other fixed sets of data.
Let me know if you need further explanations or more examples! ?