Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting String value from enum in Java

Tags:

java

enums

I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?

I can get the int values of the statuses but would like the option of getting the string values from the ints as well.

public enum Status {     PAUSE(0),     START(1),     STOP(2);      private final int value;      private Status(int value) {         this.value = value     }      public int getValue() {         return value;     } } 
like image 690
Mozbi Avatar asked Jul 19 '13 08:07

Mozbi


People also ask

Can enum value be string?

Java provides a valueOf(String) method for all enum types. Thus, we can always get an enum value based on the declared name: assertSame(Element.LI, Element. valueOf("LI"));

Can we use enum as string in Java?

Enum to String Conversion Example in JavaThere are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.

How do you check if a string is present in an enum Java?

Then you can just do: values. contains("your string") which returns true or false.


2 Answers

if status is of type Status enum, status.name() will give you its defined name.

like image 107
harsh Avatar answered Sep 30 '22 09:09

harsh


You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

like image 41
Juvanis Avatar answered Sep 30 '22 11:09

Juvanis