Login Register
×

What is an Enum in Java?

What is an Enum?

In Java, an enum is a special type that allows you to create a fixed set of values with meaningful names.

Think of an enum as a list of options that cannot change. For example: days of the week (MONDAY, TUESDAY…) or directions (NORTH, SOUTH, EAST, WEST).

An enum (short for enumeration) is a special type used to define a group of fixed constants under a single name.

For example, if you want to represent days of the week or directions like NORTH, SOUTH, EAST, WEST, using an enum is the best and most readable way.

Features of Enums in Java

1) Type-Safe Constants: Enums provide a type-safe way to define a fixed set of values. You can only use the constants defined in the enum, which prevents errors from using invalid values.

enum Direction { NORTH, SOUTH, EAST, WEST }

Direction myDir = Direction.NORTH; // Only values from Direction can be used

2) Implicitly Static and Final: All enum constants are automatically static and final.

3) Methods and Fields: Enums can include fields, constructors, and methods, making them more powerful than simple constants.

For example:

enum Planet {
EARTH(5_972), MARS(641);

private int mass; // mass in kilograms

Planet(int mass) {
this.mass = mass; // Constructor
}

int getMass() {
return mass; // Method to access field
}
}

4) Implements Interfaces: Enums can implement interfaces to provide extra functionality. This allows enums to behave like classes in some ways while still being constants.

5) Switch Statement Compatibility: Enums can be used directly in switch statements, making code cleaner and more readable.

Example:

Direction dir = Direction.EAST;

switch(dir) {
    case NORTH -> System.out.println("Going up!");
    case SOUTH -> System.out.println("Going down!");
    case EAST  -> System.out.println("Going right!");
    case WEST  -> System.out.println("Going left!");
}

Syntax of Enum in Java

An enum is declared using the enum keyword, followed by a name and a list of constants separated by commas.

enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}

Example: Declaring days of the week

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

How to Use Enums in Java

1) Access Enum Values

You can use enum constants by referring to their name.

public class Main {
public static void main(String[] args) {
Day today = Day.FRIDAY; // Assign enum value
System.out.println("Today is: " + today);
}
}

Output:

Today is: FRIDAY

Enum in Switch Statements

We can directly used switch statements in Java, which makes your conditional logic cleaner and easier to read.

Example: Enum in a Switch Statement

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

public class Main {
public static void main(String[] args) {
Day today = Day.SATURDAY; // Assign an enum value

switch(today) {
case MONDAY:
System.out.println("Back to work!");
break;
case FRIDAY:
System.out.println("Weekend is near!");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Enjoy the weekend!");
break;
default:
System.out.println("It's a regular weekday.");
}
}
}

Output:

Enjoy the weekend!

How To Adding Methods to Enums in Java

Enums can also contain methods, fields, and constructors.

Example: Enum with a Method

enum Season {
SPRING("Warm weather"),
SUMMER("Hot weather"),
FALL("Cool weather"),
WINTER("Cold weather");

// Private field to store extra info about the season
private String description;

// Private constructor to initialize the field
private Season(String description) {
this.description = description;
}

// Public method to get the description
public String getDescription() {
return description;
}
}

public class Main {
public static void main(String[] args) {
// Loop through all enum constants
for (Season season : Season.values()) {
System.out.println(season + " → " + season.getDescription());
}
}
}

Output:

SPRING → Warm weather
SUMMER → Hot weather
FALL → Cool weather
WINTER → Cold weather

Essentials Enum Methods in Java

  1. values(): The values() method returns an array of all constants defined in the enum. You can use it to loop through each value one by one.
  2. ordinal():The ordinal() method returns the index (position) of an enum constant, that starting from 0.
  3. valueOf(String name): The valueOf() method converts a string name into its matching enum constant. If the name doesn’t match any constant, it throws an error.

Example: Using Enum Methods

enum Color {
RED, GREEN, BLUE;
}

public class Main {
public static void main(String[] args) {

// 1. values() method – print all colors
System.out.println("All colors:");
for (Color color : Color.values()) {
System.out.println("- " + color);
}

// 2. ordinal() method – show position of a color
Color selectedColor = Color.GREEN;
System.out.println("\nPosition of " + selectedColor + ": " + selectedColor.ordinal());

// 3. valueOf() method – convert string to enum
String colorName = "RED";
Color chosen = Color.valueOf(colorName);
System.out.println("\nColor from string: " + chosen);
}
}

Output:

All colors:
- RED
- GREEN
- BLUE

Position of GREEN: 1

Color from string: RED

Also Learn Important Topics of Java