PAA
PAA

Reputation: 12063

Syntax error on token "1", Identifier expected in Enum Java

I want to implement Enum for Number, I want to get its respective String values. I already followed link: http://www.makeinjava.com/convert-enum-integer-string-value-java/.

The error which I'm getting is

Syntax error on token "1", Identifier expected

Syntax error on token "2", Identifier expected

public enum CompanyCityType {
    1("New York"),
    2("Reston");
    
    private Integer companyCityType;

    CompanyCityType(Integer companyCityType) {
        this.companyCityType = companyCityType;
    }

    public Integer getCompanyAddrType() {
        return this.companyCityType;
    }
}

Upvotes: 1

Views: 1934

Answers (1)

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

You cannot begin any identifier name in Java with a number, it must follow the rules as specified for having a valid variable name in Java.

As per the Oracle variable tutorial:

Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_".

As the fields in an enum are actually public static final fields (singleton instances) or class variables they follow the same set of naming rules as a normal Java variable.

You need to refactor your code to:

public enum CompanyCityType {

    NEW_YORK(1),
    RESTON(2);

    private int companyCityType;

    CompanyCityType(int companyCityType) {
        this.companyCityType = companyCityType;
    }

    public int getCompanyAddrType() {
        return this.companyCityType;
    }
}

Upvotes: 2

Related Questions