Java Enums

What is an Enum in Java?

In Java, an enum is a special data type that represents a collection of constants. Each constant in an enum is an instance of the enum type, making it type-safe and more readable. Enums are used when you have a fixed set of predefined values, such as days of the week, months or directions.

Key Features of Enums in Java

  1. Type-Safe Constants: Enums provide a type-safe way to define a fixed set of constants.
  2. Implicitly Static and Final: Enum constants are static and final, ensuring immutability.
  3. Methods and Fields: Enums can have methods, fields, and constructors.
  4. Implements Interfaces: Enums can implement interfaces to provide additional functionality.
  5. Switch Statement Compatibility: Enums can be used in switch statements for cleaner code.

Syntax of Enum

enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}

Example: Enum Declaration

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

How to Use Enums in Java

Access Enum Values

You can access enum constants using their name:

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

Output:

Today is: MONDAY

Enum in Switch Statements

Enums work seamlessly with switch statements, simplifying conditional logic.

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.FRIDAY;

switch (today) {
case MONDAY:
System.out.println("Start of the work week.");
break;
case FRIDAY:
System.out.println("Weekend is near!");
break;
case SUNDAY:
System.out.println("Relax, it's Sunday!");
break;
default:
System.out.println("It's a weekday.");
}
}
}

Output:

Weekend is near!

Adding Methods to Enums

Enums can have methods to provide additional functionality.

Example: Enum with a Method

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

public boolean isWeekend() {
return this == SATURDAY || this == SUNDAY;
}
}

public class Main {
public static void main(String[] args) {
Day today = Day.SATURDAY;
System.out.println("Is it weekend? " + today.isWeekend());
}
}

Output:

Is it weekend? true

Enum with Constructors, Fields and Methods

Enums can have private fields, constructors, and methods to associate additional information with each constant.

Example: Enum with Additional Fields

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

private String description;

// Constructor
private Season(String description) {
this.description = description;
}

public String getDescription() {
return description;
}
}

public class Main {
public static void main(String[] args) {
for (Season season : Season.values()) {
System.out.println(season + ": " + season.getDescription());
}
}
}

Output:

SPRING: Warm
SUMMER: Hot
FALL: Cool
WINTER: Cold

Enum Methods

  1. values(): Returns an array of all enum constants.
  2. ordinal(): Returns the position (index) of an enum constant.
  3. valueOf(String name): Returns the enum constant with the specified name.

Example: Using Enum Methods

enum Color {
RED, GREEN, BLUE;
}

public class Main {
public static void main(String[] args) {
// values() method
for (Color color : Color.values()) {
System.out.println(color);
}

// ordinal() method
Color selectedColor = Color.GREEN;
System.out.println("Index of GREEN: " + selectedColor.ordinal());

// valueOf() method
Color colorFromString = Color.valueOf("RED");
System.out.println("Color from string: " + colorFromString);
}
}

Output:

RED
GREEN
BLUE
Index of GREEN: 1
Color from string: RED

When to Use Enums?

  • Predefined Constants: Use enums for fixed values like days, months or directions.
  • Switch Statements: Enums make switch statements more readable and manageable.
  • Type Safety: Enums enforce type safety, reducing errors caused by invalid constants.

Advantages of Enums

  1. Improves Code Readability: Enums make code more self-explanatory.
  2. Enhances Type Safety: Prevents invalid values from being used.
  3. Simplifies Code Maintenance: Centralizes constant values in one place.
  4. Supports Advanced Features: Allows methods, fields and constructors for extended functionality.

Leave a Comment