Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from a Java enum

Tags:

I have a enum which looks like:

public enum Constants{
  YES("y"), NO("N")
  private String value;

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

I have a test class which looks like

public class TestConstants{
 public static void main(String[] args){
   System.out.println(Constants.YES.toString())
   System.out.println(Constants.NO.toString())
 }
}

The output is:

YES
NO

instead of

Y
N

I am not sure what is wrong here ??

like image 247
Mandar Avatar asked Feb 01 '16 21:02

Mandar


People also ask

How do you find the value of an enum?

To get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

How can I lookup a Java enum from its string value?

Example: Lookup enum by string value We then use the enum TextStyle's valueOf() method to pass the style and get the enum value we require. Since valueOf() takes a case-sensitive string value, we had to use the toUpperCase() method to convert the given string to upper case.

What does enum valueOf return?

valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)

How do you iterate over an enum?

Enums don't have methods for iteration, like forEach() or iterator(). Instead, we can use the array of the Enum values returned by the values() method.


1 Answers

You need to override the toString method of your enum:

public enum Constants{
    YES("y"), NO("N")

    // No changes

    @Override
    public String toString() {
        return value;
    }
}
like image 115
Mohammed Aouf Zouag Avatar answered Sep 22 '22 04:09

Mohammed Aouf Zouag