What is an Enum? Write a program that displays enumeration constants using the values() and valueOf() methods

1.A] What is an Enum? Write a program that displays enumeration constants using the values() and valueOf() methods.

Answer:

What is an Enum?

An Enum (short for Enumeration) in Java is a special data type that enables for a variable to be a set of predefined constants. It is used to represent a fixed set of constants, such as days of the week, directions, or seasons. Enums are type-safe, meaning you can only assign values that are within the predefined set, preventing errors caused by invalid values.

Example Program:

Here is a simple Java program that demonstrates the use of Enum, including the values() and valueOf() methods.

// Define an enum named Day with constants representing the days of the week
enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

public class EnumExample {
    public static void main(String[] args) {
        // Use the values() method to get an array of all enum constants
        Day[] daysOfWeek = Day.values();

        // Display each constant using a loop
        System.out.println("Days of the week:");
        for (Day day : daysOfWeek) {
            System.out.println(day);
        }

        // Use the valueOf() method to convert a string to an enum constant
        Day today = Day.valueOf("MONDAY");

        // Display the result
        System.out.println("\nToday is: " + today);
    }
}

Explanation:

  1. Enum Declaration:
  • enum Day defines an enumeration called Day with constants representing the days of the week.
  1. Using values() Method:
  • The values() method returns an array of all the constants in the enum. This is used to loop through and print each day.
  1. Using valueOf() Method:
  • The valueOf() method converts a string to the corresponding enum constant. In this case, the string “MONDAY” is converted to the MONDAY constant.

Output:

When you run the program, you will get the following output:

Days of the week:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY

Today is: MONDAY

This program demonstrates the basic usage of Enums in Java, showing how to list all enum constants and how to convert a string to an enum constant.

Leave a Reply

Your email address will not be published. Required fields are marked *