user2932566
user2932566

Reputation: 97

Questions about Enums in Java

How can I say something like:

 System.out.println(Enum.ATESTSTRING + " is a test string!");

and not:

 System.out.println(Enum.ATESTSTRING.getString() + " is a test string!");

Thanks!

Upvotes: 1

Views: 73

Answers (3)

Rohit Jain
Rohit Jain

Reputation: 213371

Override toString() method in your enum:

enum MyEnum {
    ATESTSTRING("A test String");

    private final String value;

    MyEnum(String value) { this.value = value; }

    @Override
    public String toString() {return value; }
}

Upvotes: 6

Radiodef
Radiodef

Reputation: 37875

By default Enum#toString will return its name. You should be able to just do your first expression. The String concatenation (+ operator) will call toString automatically.

enum TestEnum {
    ATESTSTRING;

    public static void main(String[] args) {
        System.out.println(ATESTSTRING + " is a test string");
    }
}

Will output ATESTSTRING is a test string.

Upvotes: 0

mdl
mdl

Reputation: 426

Enum.ATESTSTRING.toString() or Enum.ATESTSTRING.name() (if you want to use your toString() for something else).

The name() method belongs to the Enum class, so all enum values automatically have this method available.

Upvotes: 1

Related Questions