Get startedGet started for free

Introduction to Enums

1. Introduction to Enums

We've learned how to work with dates and times in Java. Now, let’s explore `Enums`, a useful feature for representing a fixed set of values. `Enums` help make code more readable and prevent invalid values from being used in programs.

2. Why Use Enums?

In programming, we often need a predefined list of values, like days of the week or user roles. Instead of using strings or numbers, `Enums` allow us to define a fixed set of constants. This makes our code more readable and prevents invalid values from being used. Unlike other programming languages, Enums are built into Java, meaning we do not need to import anything to use them.

3. Defining an Enum

`Enums` are defined using the `enum` keyword. Each value in an Enum is a constant, written in uppercase by convention. In this example, Day represents the days of the week, ensuring only valid days can be used in our program.

4. Using Enums in a program

Once an `Enum` is defined, we can use it like a regular variable. In this example, we create a variable today of type `Day` and assign it the value `Day.WEDNESDAY`. Printing `today` displays the `Enum` value.

5. Looping through Enum values

If we want to see what values are defined in an `enum`, we can use the `.values()` method. This method allows us to iterate through all `Enum` values. `.ordinal()` returns the index of each `enum` constant, starting from `0`. Here, we reused the `enum` named `Day` with values representing weekdays. The `for-each` loop iterates through `Day.values()`, printing each constant and its corresponding index. For example, `MONDAY` is at index `0`, `TUESDAY` at index `1`, and so on. This method is particularly useful when we need to associate values with numerical positions in an `Enum`.

6. Enum with methods

`Enums` in Java can store additional data and behaviors by defining methods within them. The `Status` `enum` contains two constants, `SUCCESS` and `ERROR`, each associated with a message. The constructor assigns a message to each constant upon initialization. The message variable holds a custom description for each status, such as `Operation successful` The `getMessage()` method allows retrieving the description when needed. Let's look at an example usage for this `enum`.

7. Enum with methods

In this example, we first define an instance of the `Status` enum named `status` and assign it the value `SUCCESS`. Then, we print the `enum` object itself, which outputs `SUCCESS` - the name of the constant. Finally, we call `.getMessage()` to print the description - `Operation successful` `Enums` with methods are useful when constants need additional properties, such as messages, error codes, or formatted labels.

8. Let's practice!

Now it is your time to practice!