In Java, you can use an enum
type to define a set of constant values, each of which has a name and an associated value. You can use the name()
method of the Enum
class to get the name of an enum
value as a String
, and the toString()
method to get the String
representation of an enum
value.
Here's an example of how to use String
values with an enum
in Java:
public enum Size { SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL"); private String abbreviation; private Size(String abbreviation) { this.abbreviation = abbreviation; } public String getAbbreviation() { return abbreviation; } public static void main(String[] args) { Size size = Size.LARGE; String name = size.name(); // name is "LARGE" String toString = size.toString(); // toString is "LARGE" String abbreviation = size.getAbbreviation(); // abbreviation is "L" System.out.println(name); System.out.println(toString); System.out.println(abbreviation); } }
In this example, the Size
enum
has four constant values: SMALL
, MEDIUM
, LARGE
, and EXTRA_LARGE
. Each enum
value has an associated String
value that is stored in the abbreviation
field.
The name()
method is called on the size
variable and returns the name of the enum
value as a String
. The toString()
method is called on the size
variable and returns the String
representation of the enum
value. The getAbbreviation()
method is a custom method that returns the abbreviation
field of the enum
value.
You can use these methods to work with String
values and enum
values in Java. The name()
and toString()
methods are useful for displaying the enum
values in a user-friendly way, and the getAbbreviation()
method is an example of a custom method that you can use to access the additional information associated with an enum
value.