Java Enums
100%

Java Enums

In Java, an enum (enumeration) is a special type used to define a fixed set of constants. Enums make programs easier to read, understand, and maintain.

1. What Is an Enum?

An enum is useful when a variable should contain only a limited number of predefined values, such as days, months, directions, or order statuses.

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

Here, Day can represent one of the seven days.

2. Creating and Using an Enum

Declare an enum and use its constants with the enum name.

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);
    }
}
Output:
MONDAY
Remember: Use the enum name followed by a dot and the constant name, such as Day.MONDAY.
3. Enum Constants

Enum constants are fixed values declared inside an enum. By convention, their names are written in uppercase.

enum TrafficLight {
    RED, YELLOW, GREEN
}

public class Main {
    public static void main(String[] args) {
        TrafficLight light = TrafficLight.GREEN;

        System.out.println("Signal: " + light);
    }
}
Output:
Signal: GREEN
4. Enum in an If-Else Statement

Enums can be checked using if-else statements.

enum Level {
    LOW, MEDIUM, HIGH
}

public class Main {
    public static void main(String[] args) {
        Level level = Level.HIGH;

        if (level == Level.HIGH) {
            System.out.println("High level selected");
        } else {
            System.out.println("Another level selected");
        }
    }
}
Output:
High level selected
5. Enum with a Switch Statement

An enum works well with a switch statement when different constants require different actions.

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
}

public class Main {
    public static void main(String[] args) {
        Day day = Day.MONDAY;

        switch (day) {
            case MONDAY:
                System.out.println("Start of the week");
                break;

            case TUESDAY:
                System.out.println("Second day");
                break;

            case WEDNESDAY:
                System.out.println("Middle of the week");
                break;
        }
    }
}
Output:
Start of the week
6. Using the values() Method

The values() method returns an array containing all enum constants in their declared order.

enum Color {
    RED, GREEN, BLUE
}

public class Main {
    public static void main(String[] args) {
        for (Color c : Color.values()) {
            System.out.println(c);
        }
    }
}
Output:
RED
GREEN
BLUE
7. Using the valueOf() Method

The valueOf() method converts an exact constant name into its corresponding enum value.

enum Size {
    SMALL, MEDIUM, LARGE
}

public class Main {
    public static void main(String[] args) {
        Size s = Size.valueOf("MEDIUM");

        System.out.println(s);
    }
}
Output:
MEDIUM
The string must match the constant name exactly. For example, Size.valueOf("medium") throws IllegalArgumentException.
8. Using ordinal()

The ordinal() method returns the zero-based position of an enum constant in its declaration.

enum Level {
    LOW, MEDIUM, HIGH
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Level.LOW.ordinal());
        System.out.println(Level.MEDIUM.ordinal());
        System.out.println(Level.HIGH.ordinal());
    }
}
Output:
0
1
2
Avoid using ordinal positions as permanent IDs because changing the declaration order changes those positions.
9. Enum with a Constructor

An enum can have a constructor to store additional information for each constant. Enum constructors cannot be public or protected.

enum Course {
    JAVA("Programming"),
    PYTHON("Programming"),
    HTML("Web Development");

    private String category;

    Course(String category) {
        this.category = category;
    }

    public String getCategory() {
        return category;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Course.JAVA.getCategory());
        System.out.println(Course.HTML.getCategory());
    }
}
Output:
Programming
Web Development
10. Enum with Fields and Methods

Enums can contain fields, constructors, and methods, just like classes.

enum Status {
    PENDING("Waiting"),
    APPROVED("Accepted"),
    REJECTED("Declined");

    private String message;

    Status(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

public class Main {
    public static void main(String[] args) {
        Status s = Status.APPROVED;

        System.out.println(s);
        System.out.println(s.getMessage());
    }
}
Output:
APPROVED
Accepted
11. Comparing Enum Values

Enum constants are unique instances. You can compare them using == or equals().

enum Direction {
    NORTH, SOUTH, EAST, WEST
}

public class Main {
    public static void main(String[] args) {
        Direction d1 = Direction.NORTH;
        Direction d2 = Direction.NORTH;
        Direction d3 = Direction.SOUTH;

        System.out.println(d1 == d2);
        System.out.println(d1 == d3);
    }
}
Output:
true
false
12. Enum vs String
Enum String
Represents predefined constants Stores text
Restricts values to declared constants Can contain many different text values
Example: Day.MONDAY Example: "Monday"
Useful for fixed choices Useful for general text
13. Java Enum Assignments
  1. Create an enum named Weekday with all seven days.
  2. Create an enum named Season with four seasons and print one season.
  3. Create an enum named TrafficLight and use a switch statement to display an instruction.
  4. Use values() to print all constants of a Month enum.
  5. Use valueOf() to convert the string "LARGE" into an enum value.
  6. Use ordinal() to display the positions of three enum constants.
  7. Create a PaymentStatus enum with PENDING, PAID, and FAILED.
  8. Create a Course enum with a field storing each course's fee and a method to display it.
  9. Compare two enum variables using ==.
  10. Create an enum named OrderStatus and print a suitable message for each status.

Quick Quiz: Java Enums

Select the correct answer for each question.

1. What is an enum in Java?



2. Which method returns all enum constants as an array?



3. What is the ordinal() value of the first enum constant?