CodeGym /Courses /JAVA 25 SELF /Enumeration: enum

Enumeration: enum

JAVA 25 SELF
Level 10, Lesson 4
Available

1. Introduction

In programming, you often have to operate on lists of predefined, limited options. For example: days of the week, traffic light colours, game difficulty levels, order statuses. Each of these options is usually represented by a fixed value. That brings us closer to today’s topic — enumerations (enum).

An enumeration is a special data type that lets you declare a set of named constants.

enum is like a box with labelled compartments, where each label is a unique name associated with a number.

Key benefits of enum:

  • Your code becomes readable and self-documenting;
  • Instead of mysterious “magic numbers” like 0, 1, 2, you get expressive names: DayOfWeek.MONDAY or TrafficLight.RED;
  • The compiler will complain if you try to assign an invalid value;
  • Under the hood, each element is represented by an ordinary integer! (We’ll come back to this.)

Syntax for declaring an enum


// General template for declaring an enumeration
public enum Name
{
    CONSTANT1 ,
    CONSTANT2 ,
    CONSTANT3
}
Enum declaration syntax

Declaring an enumeration in Java is very simple. Here is a basic example:

// File DayOfWeek.java
public enum DayOfWeek {
    MONDAY,			// 0	
    TUESDAY,		// 1
    WEDNESDAY,		// 2
    THURSDAY,		// 3
    FRIDAY,			// 4
    SATURDAY,		// 5
    SUNDAY			// 6
}

Explanation:

  • The enum keyword tells the compiler: “This is an enumeration!”
  • Inside curly braces, the variant names (constants) are listed, separated by commas.
  • By convention, names are written in UPPER_SNAKE_CASE (all caps, words separated by underscores).

Where can you declare an enum?

  • In a separate file (DayOfWeek.java).
  • Inside a class (if you need a private enumeration only for that class).
  • Even inside a method (though that’s rare).

2. Using enums in code

Declaring an enum variable:

DayOfWeek today = DayOfWeek.MONDAY;

Now today can take only one of the values declared in DayOfWeek.

Example of using with switch

switch (today) 
{
    case MONDAY:
        System.out.println("Oh, Monday...");
        break;
    case FRIDAY:
        System.out.println("Hooray, Friday!");
        break;
    default:
        System.out.println("Just a regular day.");
}

Important distinction: in a case label, you write just the constant’s name (without a prefix) if the variable type is already known to the compiler.

Iterating over all enum values

Every enum has a static method values() that returns an array of all its values:

for (DayOfWeek day : DayOfWeek.values()) 
{
    System.out.println(day);
}

This is very handy for printing menus, validation, generating options, etc.

3. Enum methods: name(), ordinal(), valueOf()

Enums in Java are not just lists of constants but full-fledged classes with methods!

Method name()

Returns the constant’s name as a string (as written in code):

DayOfWeek day = DayOfWeek.FRIDAY;
System.out.println(day.name()); // "FRIDAY"

Method ordinal()

Returns the ordinal number of the constant (zero-based):

System.out.println(DayOfWeek.MONDAY.ordinal()); // 0
System.out.println(DayOfWeek.FRIDAY.ordinal()); // 4

Warning: You shouldn’t store or compare enums by ordinal() if the order might change in the future! Use names instead.

Method valueOf(String name)

Converts a string to an enum value if such a constant exists:

DayOfWeek day = DayOfWeek.valueOf("MONDAY");
System.out.println(day); // MONDAY

If the strings don’t match, an IllegalArgumentException will be thrown.

Method values()

Returns an array of all enum values (an example was shown above):

DayOfWeek[] days = DayOfWeek.values();

4. Enum with fields, a constructor, and methods

Enums in Java can be extended: add fields, constructors, methods! Yes, it’s not just a list of names but a mini-class.

Example: days of the week with a localized name

public enum DayOfWeek 
{
    MONDAY("Monday"),
    TUESDAY("Tuesday"),
    WEDNESDAY("Wednesday"),
    THURSDAY("Thursday"),
    FRIDAY("Friday"),
    SATURDAY("Saturday"),
    SUNDAY("Sunday");

    private final String russianName;

    // Constructor (private by default)
    DayOfWeek(String russianName) 
    {
        this.russianName = russianName;
    }

    public String getRussianName() 
    {
        return russianName;
    }
}

You’ll learn more about how this works when we start studying OOP at levels 27+ :P

Now you can do this:

DayOfWeek day = DayOfWeek.WEDNESDAY;
System.out.println(day.getRussianName()); // "Wednesday"

Pro tip: Each enum value can have its own data (in this case — the Russian name).

Advantages of using enums

  • Type safety: you can’t accidentally assign an enum variable a value that isn’t in the list.
  • Readability: the code documents itself (TrafficLight.RED instead of 1 or "red").
  • Ease of maintenance: if you need to add or remove an option, you do it in one place.
  • Works with switch: enum is perfect for branching on values.
  • Extensible: add fields, methods, implement interfaces.
  • Fewer bugs: the compiler helps you handle all cases (especially in switch constructs).

6. Practice: use enum in our application

Let’s add support for days of the week to our mini-application using an enum.

Step 1. Declare an enum

public enum DayOfWeek 
{
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Step 2. Use it in code

System.out.println("Enter a day of the week (e.g., MONDAY):"); 
Scanner console = new Scanner(System.in);                      
String input = console.nextLine().toUpperCase();               
                                                               
DayOfWeek day = DayOfWeek.valueOf(input);                      
switch (day) 
{                                                 
    case MONDAY:                                               
        System.out.println("Start of the workweek!");          
        break;                                                 
    case FRIDAY:                                               
        System.out.println("The weekend is coming soon!");     
        break;                                                 
    case SATURDAY:                                             
    case SUNDAY:                                               
        System.out.println("Hooray, the weekend!");            
        break;                                                 
    default:                                                   
        System.out.println("Just another workday.");           
}                                                              

What’s happening:

  • The user enters a day of the week (for example, "monday" or "MONDAY").
  • We convert the string to upper case (toUpperCase()) so it’s case-insensitive.
  • We convert the string to an enum value via valueOf.
  • We use switch to output a different message.
  • If the input is invalid, we catch the error and print a warning.

7. Common mistakes when working with enums

Mistake #1: Using strings or numbers instead of enums. Very often, beginners keep writing code like this:

int day = 1; // 1 — is this Monday?

or

String status = "DELIVERED";

That’s bad: you can make typos; the code is hard to maintain. Use enum!

Mistake #2: Comparing enums via == and .equals(). In Java, enum values can be compared using == — this is safe because all values are unique within the enum class:

if (day == DayOfWeek.MONDAY) { ... } // OK!

Although .equals() works too, == is used more often.

Mistake #3: Poor names for enum elements. Don’t name elements VALUE1, VALUE2, VALUE3 — a month later no one will understand what that means! Use meaningful names.

Mistake #4: Using ordinal() for logic. Don’t write this:

if (day.ordinal() == 0) { ... } // Don’t do this!

The order of elements may change, and everything will break. Use names!

1
Task
JAVA 25 SELF, level 10, lesson 4
Locked
Traffic Light Simulation 🚦
Traffic Light Simulation 🚦
1
Task
JAVA 25 SELF, level 10, lesson 4
Locked
Seasonal greetings in the app 🌸☀️🍁❄️
Seasonal greetings in the app 🌸☀️🍁❄️
1
Task
JAVA 25 SELF, level 10, lesson 4
Locked
Weekly planning in the app 🗓️
Weekly planning in the app 🗓️
1
Task
JAVA 25 SELF, level 10, lesson 4
Locked
Navigation in a Space Voyage 🚀
Navigation in a Space Voyage 🚀
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION