Enum in Java

Enum In Java

Enum is a class used to represent fix number of constant values.

Syntax

Syntax
enum VariableName{
// Data Member goes Here
member1, member2, member3, ....., member n
};

Example

enum SystemError { badFileName, timeOut, resourceNotAvailable };
public class Main {
    public static void main(String[] args) {
        printError(SystemError.badFileName);
    }
   static void printError(SystemError e) {
        if (e == SystemError.badFileName) {
            System.out.println("This is Bad File name Error");
        } else if (e == SystemError.resourceNotAvailable) {
            System.out.println("Resources not available.");
        } else if (e == SystemError.resourceNotAvailable) {
            System.out.println("No Resources available");
        }
    }
}
Show Output
  • Here, enum SystemError means our own name SystemError where we can write multiple errors inside curly brackets.
  • printError is a function that takes SystemError as a parameter and prints its custom message according to the error.
  • In main method we are calling printError function with arguments SystemError.badFileName. It prints This is bad File name error.

Why should you use Enum in Java?

When a method parameter can only take a small set of possible values like (male, female other) or (badFileName, timeOut, resourceNotAvailable). If you use enums, you increase compile-time checking and avoid errors from passing in invalid constants. You can only use what you defined.

enum SystemError { badFileName, timeOut, resourceNotAvailable };
public class Main {
    public static void main(String[] args) {
       for(SystemError s: SystemError.values()){
           System.out.println(s);
       }
    }

}
Show Output