How to create a static enum with a value that has a hyphen symbol in Java?

This is not specific to enums. This applies to all identifiers in Java: class names, method names, variable names, etcetera. Hyphens are simply not allowed. You can find all valid characters in Java Language Specification, chapter 3.8 "Identifiers".

To illustrate the problem:

int num-ber = 5;
int num = 4;
int ber = 3;

System.out.println(num-ber);

What would you expect to happen here?


This is not possible with Java, because each item has to be a valid identifier (and valid Java identifiers may not contain dashes).

The closest thing would be adding a custom property to each enum value or override the toString method, so you can do the following:

Test.EMPLOYEE_ID.getRealName();    // Returns "employee-id"
Test.EMPLOYEE_CODE.getRealName();  // Returns "employeeCode"

public enum Test
    EMPLOYEE_ID("employee-id"),
    EMPLOYEE_CODE("employeeCode");

    private Test(String realName) {
        this.realName = realName;
    }
    public String getRealName() {
        return realName;
    }
    private final String realName;
}

Tags:

Java

Enums