</>
Skip to content
Java lessons (34/47)

Java — Enums

Basic enum

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        System.out.println(today); // MONDAY
        System.out.println(today.ordinal()); // 0
    }
}

Enum with fields

enum Color {
    RED(255, 0, 0),
    GREEN(0, 255, 0),
    BLUE(0, 0, 255);

    final int r, g, b;

    Color(int r, int g, int b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }

    String toHex() {
        return String.format("#%02X%02X%02X", r, g, b);
    }
}

Enum in switch

enum Season { SPRING, SUMMER, AUTUMN, WINTER }

String describe(Season s) {
    return switch (s) {
        case SPRING -> "Flowers bloom";
        case SUMMER -> "Sun is hot";
        case AUTUMN -> "Leaves fall";
        case WINTER -> "Snow falls";
    };
}

Enum with abstract methods

enum Operation {
    ADD {
        public double apply(double a, double b) { return a + b; }
    },
    SUBTRACT {
        public double apply(double a, double b) { return a - b; }
    },
    MULTIPLY {
        public double apply(double a, double b) { return a * b; }
    };

    public abstract double apply(double a, double b);
}

EnumSet and EnumMap

import java.util.*;

EnumSet<Day> weekdays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);

EnumMap<Day, String> schedule = new EnumMap<>(Day.class);
schedule.put(Day.MONDAY, "Meeting");
schedule.put(Day.FRIDAY, "Review");

Mini Practice

Write Java code that:

  1. Creates an enum with fields and constructor
  2. Uses an enum in a switch expression
  3. Uses EnumSet for a group of enum values

Up Next

In the next lesson, you'll learn about Exceptions — error handling in Java.

Related Topics

Frequently Asked Questions about Enums

What is Enums in Java?

Enums is a fundamental concept in Java. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Enums?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Enums.

Why is Enums important in Java?

Enums is essential for Java development. Understanding this concept will help you write better code and solve real-world problems more effectively.