0

I have a set of integer values which I need to define as a part of enum, I'm doing this.

public enum Test{

    763("763"),
    1711("1711"),
    8050("8050"),
    9311("9311");

    private Integer test;

    Test(Integer test) {
        this.test= test;
    }

    public Integer getTest() {
        return test;
    }

}

It gives me unexpected token on the first line.. What is missing here?

Thanks in advance.

3
  • Rule #1: All variable names must begin with a letter of the alphabet, an underscore, or (_), or a dollar sign ($). The convention is to always use a letter of the alphabet. The dollar sign and the underscore are discouraged. You defined a constructor passing an Integer Object but in the Enum list you passed a String Object. Commented Jun 17, 2020 at 4:53
  • @mashkum why do you want to do that? Commented Jun 17, 2020 at 4:57
  • Why exactly do you want to have enum constants with a name that is a number – what is the business context here? Commented Jun 17, 2020 at 5:02

2 Answers 2

3

Java does not allow variables to start with a number. Take a look at the official variable rules. Furthermore, you should pass test as an integer and not as a String.

A working solution might look like the following:

public enum Test {
  T_763(763),
  T_1711(1711),
  T_8050(8050),
  T_9311(9311);

  private Integer test;

  Test(Integer test) {
    this.test = test;
  }

  public Integer getTest() {
    return test;
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

The underscore is bad style, though. It should be avoided.
1
  1. Typo with opening curly brace in constructor
  2. Enumerations themselves can't be numbers (these are names that can't be numbers in java)
  3. The value is declared integer but you pass String.

Here is a fixed version of what you're trying to do:

public enum Test {
    T_763(763),
    T_1711(1711),
    T_8050(8050),
    T_9311(9311);

    private final Integer test;
    Test(Integer test) {
        this.test= test;
    };
    public Integer getTest() {
        return test;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.