In Java, you can use an enumeration (enum
) to define a set of named constants. An enum
is a special data type that allows you to define a set of named constants in a single data type.
To use an enum
to define a set of named constants, you can define an enum
type with the enum
keyword, and then specify the constants as a list of values within curly braces.
Here is an example of how you can define an enum
type called Color
that represents a set of named color constants:
public enum Color { RED, GREEN, BLUE }
To use the Color
enum
, you can declare a variable of type Color
and assign it one of the named constants.
Here is an example of how you can use the Color
enum
:
public class MyClass { public static void main(String[] args) { Color myColor = Color.RED; System.out.println(myColor); // Outputs "RED" } }
In this example, the myColor
variable is declared as type Color
and is assigned the value Color.RED
. The Color
enum
defines the named constants RED
, GREEN
, and BLUE
, so you can assign one of these constants to a variable of type Color
. When the value of the myColor
variable is printed to the console, it outputs "RED" because that is the constant that was assigned to it.
It is important to note that the constants defined in an enum
are automatically assigned an integer value starting from 0, so in this example, RED
is assigned the value 0, GREEN
is assigned the value 1, and BLUE
is assigned the value 2. However, you can also specify custom values for the constants if you want.