Java Enum with Values Getter methods and Constructor

Tags: enum

In this Java core tutorial, we learn how to define a new enum in Java with constructor and getter methods.

Define new enum with constructor and getter methods.

ResultCode.java

public enum ResultCode {
    SUCCESS(200, "Success"),
    FAILED(500, "Server Error"),
    VALIDATE_FAILED(404,"Validated Failed"),
    UNAUTHORIZED(401,"Un Authorized"),
    FORBIDDEN(403,"Forbidden");

    private int code;
    private String message;

    private ResultCode(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

How to use the ResultCode enum above

ResultCodeExample.java

public class ResultCodeExample {
    public static void main(String... args) {
        ResultCode success = ResultCode.SUCCESS;
        ResultCode unauthorized = ResultCode.UNAUTHORIZED;

        System.out.println(success);
        System.out.println(success.getCode());
        System.out.println(success.getMessage());

        System.out.println(unauthorized);
        System.out.println(unauthorized.getCode());
        System.out.println(unauthorized.getMessage());
    }
}
The output is:
SUCCESS
200
Success
UNAUTHORIZED
11
Un Authorized

Happy Coding 😊

Java Get Enum Value by String