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 ??
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.
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.
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.)
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With