Java Program to pick random value from enumerations

Program

import java.util.Random;
public class RandomAnswers
{
    public enum Answers{
        NO, YES, MAYBE, LATER, SOON, NEVER
    }
    public static void main(String[] args)
    {
        final Answers[] VALUES = Answers.values();
        final int SIZE = VALUES.length;
        final Random RANDOM = new Random();
        System.out.println(VALUES[RANDOM.nextInt(SIZE)]);
    }
}

This program demonstrates how to pick a random value from an enumeration (enum) in Java.

  1. Enumeration Answers:

    • The Answers enum defines six possible values: NO, YES, MAYBE, LATER, SOON, and NEVER.
    • Enumerations in Java are a special type of class that represents a group of constants.
  2. Main Method:

    • The program uses the main() method to randomly pick and display one of the values from the Answers enum.
  3. Steps in main() Method:

    • Retrieve All Enum Values:
      • Answers.values() returns an array containing all the constants in the Answers enum ([NO, YES, MAYBE, LATER, SOON, NEVER]).
      • The array is stored in the VALUES variable.
    • Find the Number of Constants:
      • VALUES.length gets the total number of constants in the enum, which is stored in the SIZE variable.
    • Generate a Random Index:
      • A Random object is created using new Random().
      • The method RANDOM.nextInt(SIZE) generates a random integer between 0 (inclusive) and SIZE (exclusive). This ensures the index is valid for the VALUES array.
    • Pick a Random Value:
      • A random constant from the VALUES array is selected using the generated index and printed to the console.

Each time the program runs, the output might differ because the value is chosen randomly.

  1. Enums in Java:

    • Enums are used to define a fixed set of constants.
    • The method values() returns an array of all the enum constants.
  2. Using Random Class:

    • The Random class is used to generate random numbers.
    • The nextInt(SIZE) method generates a random integer between 0 (inclusive) and SIZE (exclusive), which is perfect for indexing the array of enum constants.
  3. Accessing Enum Values:

    • The program accesses an enum constant by using its index in the array returned by values().

Advantages of Using Enums:

  • Enums ensure type safety by restricting the values to the predefined constants.
  • They make the code more readable and maintainable compared to using plain strings or integers.

Output

$ java RandomAnswers
YES
$ java RandomAnswers
NO
$ java RandomAnswers
NEVER
$ java RandomAnswers
LATER