Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Enum in Java – Basics of Enumeration [With Examples]

Basics of SQL
Basics of SQL
icon
12 Hrs. duration
icon
12 Modules
icon
2600+ Learners
logo
Start Learning

In Java language, enumeration is commonly referred to as enums. Enums are special data types in Java that allow for the definition of a set of named constants. They are very useful when you have a fixed set of related constants that make your code more readable and less error-prone. This article explains the basics of enums in Java and their usage and provides examples to illustrate their functionality.

What is enum?

In the Java language, an enum is a special data type that represents a group of constants(unchangeable variables, like final variables). It is used to define a collection of named constants that can be assigned to variables. Enums are very useful when you have a fixed set of related constants, such as days of the week, direction state, etc.

Declaration of enum in Java

In this section, we will define an enum in Java outside the World class. The following program demonstrates the enum in Java language:

 

Program

enum Country { CANADA, JAPAN, BRAZIL, GERMANY, INDIA }  public class Main { public static void main(String[] args) { for (Country country : Country.values()) { System.out.println(country); } } }

Output

CANADA JAPAN BRAZIL GERMANY INDIA

Declaring Enum class Inside the Class

We can also define the enum inside the class in Java. In this case, the scope of the enum is limited to that class and is used when the enum is closely related to the class and not intended to be used outside of it.

 

The following program demonstrates the declaring enum:

 

Program

public class Main { enum Country { CANADA, JAPAN, BRAZIL, GERMANY, INDIA } public static void main(String[] args) { for (Country country : Country.values()) { System.out.println(country); } } }

Output

CANADA JAPAN BRAZIL GERMANY INDIA

Enum Inside a Class

Enum can be declared within a class, just like a nested class. This encapsulates the enum within the class, making it more organized and modular. It is a common practice when the enum is closely associated with the class, enhancing readability and maintainability.

 

The following program demonstrates the enum class inside a Main class:

 

Program

public class Season { enum Month { JANUARY("Winter"), FEBRUARY("Winter"), MARCH("Spring"), APRIL("Spring"), MAY("Spring"), JUNE("Summer"), JULY("Summer"), AUGUST("Summer"), SEPTEMBER("Fall"), OCTOBER("Fall"), NOVEMBER("Fall"), DECEMBER("Winter"); private final String season; Month(String season) { this.season = season; } public String getSeason() { return season; } } private Month currentMonth; public Season(Month currentMonth) { this.currentMonth = currentMonth; } public String getMonthInfo() { return currentMonth.name() + " is in the season of " + currentMonth.getSeason(); } public void nextMonth() { int currentIndex = currentMonth.ordinal(); Month[] months = Month.values(); currentMonth = months[(currentIndex + 1) % months.length]; } public static void main(String[] args) { Season season = new Season(Month.JANUARY); System.out.println(season.getMonthInfo()); season.nextMonth(); System.out.println(season.getMonthInfo()); season.nextMonth(); System.out.println(season.getMonthInfo()); } }

Output

JANUARY is in the season of Winter FEBRUARY is in the season of Winter MARCH is in the season of Spring

Enum in a Switch Statement

Java Developers can also use enum with switch statements. It allows for clear and readable control flow based on the enum values. Let us take an example of a Month Example.

 

The following program demonstrates the switch statement with an enum:

 

Program

public class Season { // Enum declared inside the Season class enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER }  public static void printSeason(Month month) { switch (month) { case DECEMBER: case JANUARY: case FEBRUARY: System.out.println(month + " is in Winter."); break; case MARCH: case APRIL: case MAY: System.out.println(month + " is in Spring."); break; case JUNE: case JULY: case AUGUST: System.out.println(month + " is in Summer."); break; case SEPTEMBER: case OCTOBER: case NOVEMBER: System.out.println(month + " is in Fall."); break; default: System.out.println("Unknown month."); break; } }  public static void main(String[] args) { printSeason(Month.JANUARY); printSeason(Month.APRIL); printSeason(Month.AUGUST); printSeason(Month.OCTOBER); } }

Output

JANUARY is in Winter. APRIL is in Spring. AUGUST is in Summer. OCTOBER is in the Fall.
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Loop Through an Enum

We can also iterate all elements in the enum class using loops. There are two ways to do this: we can use the normal for loop or the for each loop. In the example,  we will iterate the enum element by using the loop.

 

The following program demonstrates the  enum with a loop:

 

Program

public class Season { // Enum declared inside the Season class enum Month { JANUARY("Winter"), FEBRUARY("Winter"), MARCH("Spring"), APRIL("Spring"), MAY("Spring"), JUNE("Summer"), JULY("Summer"), AUGUST("Summer"), SEPTEMBER("Fall"), OCTOBER("Fall"), NOVEMBER("Fall"), DECEMBER("Winter");   private final String season;  Month(String season) { this.season = season; }  public String getSeason() { return season; } }  public static void printAllSeasons() { // Using a for loop to iterate over all the months in the enum for (Month month : Month.values()) { System.out.println(month.name() + " is in the season of " + month.getSeason()); } }  public static void printAllSeasons2(){ Month[] month2 = Month.values() ;  for(int i = 0;i<month2.length ;i++){ System.out.println(month2[i]); } }  public static void main(String[] args) { // Call the method to print the season for each month System.out.println("First Loop"); printAllSeasons(); System.out.println("Second Loop"); System.out.println(); printAllSeasons2(); } }

Output

First Loop JANUARY is in the season of Winter FEBRUARY is in the season of Winter MARCH is in the season of Spring APRIL is in the season of Spring MAY is in the season of Spring JUNE is in the season of Summer JULY is in the season of Summer AUGUST is in the season of Summer SEPTEMBER is in the season of Fall OCTOBER is in the season of Fall NOVEMBER is in the season of Fall DECEMBER is in the season of Winter Second Loop  JANUARY FEBRUARY MARCH APRIL MAY JUNE JULY AUGUST SEPTEMBER OCTOBER NOVEMBER DECEMBER

Main Function Inside Enum

In Java, enums can have a main function. This allows them to be invoked directly from the command line. Enums are typically used to represent a set of predefined constants and encapsulate their behavior. The following program demonstrates the enum:

 

Program

public enum Operation { ADD((x, y) -> x + y), SUBTRACT((x, y) -> x - y), MULTIPLY((x, y) -> x * y), DIVIDE((x, y) -> y != 0 ? x / y : handleDivideByZero());  private final OperationStrategy strategy;  Operation(OperationStrategy strategy) { this.strategy = strategy; }  public int apply(int x, int y) { return strategy.apply(x, y); }  private static int handleDivideByZero() { System.out.println("Cannot divide by zero"); return 0; }  private interface OperationStrategy { int apply(int x, int y); }  public static void main(String[] args) { // Example usage of the enum and its apply method int resultAdd = Operation.ADD.apply(19, 30); int resultMultiply = Operation.MULTIPLY.apply(34, 72);  System.out.println("Result of ADD operation: " + resultAdd); System.out.println("Result of MULTIPLY operation: " + resultMultiply); } }

Output

Result of ADD operation: 49 Result of MULTIPLY operation: 2448

Properties of Enum in Java

There are certain properties followed by an enum, as mentioned below:

 

  • Class Type: Every enum is internally implemented as the class type.
  • Enum Constants: Each enum constant represents an object of type enum.
  • Switch Statements: Enum types can be used in switch statements.
  • Implicit Modifiers: Every enum constant is implicitly public static final. It can be accessed using the enum name. It is final, and enums cannot be extended.
  • Main Method:  Enums can declare a main() method. It allows direct invocation from the command line.

 

The following program demonstrates the implementation of the above properties:

 

Program 

import java.util.Scanner; enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } public class Main { Day day; // Constructor public Main(Day day) { this.day = day; } // Prints a line about Day using switch public void dayIsLike() { switch (day) { case MONDAY: System.out.println("Mondays are bad."); break; case FRIDAY: System.out.println("Fridays are better."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } // Driver Method in Java langauge public static void main(String[] args) { String str = "MONDAY"; Main ob = new Main(Day.valueOf(str)); ob.dayIsLike(); } }

Output

Mondays are bad.

Difference Between Enums and Classes

Feature Classes Enums
Purpose They represent a fixed set of constants They used to define objects with attributes and methods
Inheritance It cannot be extended by other classes It can be extended by other classes.
State The enum constants do not have a state The Objects of a class can maintain state through fields/attributes
Instantiation Enum instantiate during the new keyword. Enum constants are created implicitly, and the new keyword cannot be used
Example ‘enum Day {MONDAY, TUESDAY, WEDNESDAY} ‘class Car {String model; int speed;}’

Enum and Inheritance

  • Enums Cannot extend Other classes: Enums in Java implicitly extend the ‘java.lang.Enum’ class, making the final. This means you cannot extend an enum or any other class.
  • Enums can implement Interfaces: Although enums cannot extend other classes, they can implement one or more interfaces. This allows them to inherit behavior in a controlled manner.
  • State Management: Enums implementing interfaces are useful in scenarios where different states or actions need to be defined and managed in a type-safe way.

Enum and Constructor

  • We can define a constructor inside an enum to initialize fields associated with each constant.
  • In Java, we cannot instantiate new enum objects with the new keyword as we do in the case of Java class objects.
  • Each object invokes an enum constructor with its required arguments.

Conclusion

Enumeration or enums in Java provide a powerful way to define a set of named constants, making your source code more readable, maintainable, and less error-prone. Enums are more than just simple constants; they can have fields, methods, and constructors. They allow you to associate behaviors and states with specific enum values. Their ability to integrate fields methods and even implement interfaces allows enums to go beyond mere symbolic constants, serving as a sophisticated tool in your programming.

FAQs
An enum in Java is a special data type that allows you to define a set of named constants. Enums are used to represent a group of predefined constants, such as days of the week, directions, or states.
Yes, enums in Java can have methods, fields, and even constructors. This allows enums to hold additional data and behavior beyond just being constants.
Yes, an enum can implement interfaces. This allows you to enforce specific behavior across all constants in the enum.
Yes, enums in Java are type-safe. It means you can’t assign any value other than the defined constants to an enum variable.
The valueOf() method converts a string to the corresponding enum constant. If the string does not match any constant. It will throw an IllegalArgumentException.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved