Introduction to Enums

Input/Output and Streams in Java

Alex Liu

Software Development Engineer

Why Use Enums?

  • Enums define a fixed set of values
    • Example: Days of the week, Status codes
  • Improves code readability and maintainability
  • Prevents invalid values in variables
  • Notes: No import is needed, as Enums are part of core Java library
Input/Output and Streams in Java

Defining an Enum

  • Declare an Enum using enum keyword
    enum Day {
      MONDAY, 
      TUESDAY, 
      WEDNESDAY, 
      THURSDAY, 
      FRIDAY, 
      SATURDAY, 
      SUNDAY;
    }
    
  • Each value is a constant and written in uppercase
Input/Output and Streams in Java

Using Enums in a program

  • Example: Assign and print an Enum value
    public class EnumExample {
      public static void main(String[] args) {
          Day today = Day.WEDNESDAY; // Assigning an Enum value
          System.out.println("Today is: " + today);
      }
    }
    
  • Output:
    Today is: WEDNESDAY
    
Input/Output and Streams in Java

Looping through Enum values

  • Use .values() to get all values in an Enum
  • Use .ordinal() return the position of the element
  • Lets reuse the previous defined Day Enum as an example:
    for (Day d : Day.values()) {
      System.out.println(d);
      System.out.print(
      " is at index " + d.ordinal());
    }
    
  • This program will output all the values defined in the Enum:
    MONDAY is at index 0
    TUESDAY is at index 1
    WEDNESDAY is at index 2
    THURSDAY is at index 3
    FRIDAY is at index 4
    SATURDAY is at index 5
    SUNDAY is at index 6
    
Input/Output and Streams in Java

Enum with methods

  • Enums can have methods for additional functionality
enum Status {
    SUCCESS("Operation successful"),
    ERROR("An error occurred");

    private String message;
    Status(String message) {
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}
Input/Output and Streams in Java

Enum with methods

  • Example usage of Enum named Status
public class EnumMethodExample {
    public static void main(String[] args) {
        Status current = Status.SUCCESS;
        System.out.println("Status: " + current);
        System.out.println("Message: " + current.getMessage());
    }
}
  • Output:
Status: SUCCESS
Message: Operation successful
Input/Output and Streams in Java

Let's practice!

Input/Output and Streams in Java

Preparing Video For Download...