How to Convert Enum to String in Java
The Java programming language allows programs to define their own enumerated types. An object of an enumerated type contains a value drawn from a finite number of constants specified by the program. For example, you can define an enumerated type for the suit of a playing card. That enumerated type contains four elements: Club, Diamond, Heart and Spade. You can convert a Java enumerated object to the String representing the current value of the object.
Instructions
-
-
1
Declare an enumerated type as in the following sample code:
public enum Suit {
Club, Diamond, Heart, Spade
}
-
2
Declare and initialize an object of the enumerated type as in the following sample code:
Suit myCardsSuit = Diamond;
-
-
3
Convert the enumerated value to the corresponding string by calling the built-in
name() method as in the following sample code:
String myCardsSuitString = myCardsSuit.name();
For the example, String myCardsSuitString will have value "Diamond".
-
1