In Java, you can use an enum
type in a switch
statement to control the flow of execution based on the value of the enum
.
Here's an example of how to use an enum
in a switch
statement 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; switch (size) { case SMALL: System.out.println("The size is small"); break; case MEDIUM: System.out.println("The size is medium"); break; case LARGE: System.out.println("The size is large"); break; case EXTRA_LARGE: System.out.println("The size is extra large"); break; } } }
In this example, the Size
enum has four constant values: SMALL
, MEDIUM
, LARGE
, and EXTRA_LARGE
. The main()
method defines a Size
variable called size
and assigns it the value LARGE
.
The switch
statement checks the value of the size
variable, and executes the code in the corresponding case
block based on the value of the enum
. In this example, the code in the LARGE
case block is executed, and the message "The size is large" is printed.
You can use an enum
in a switch
statement in the same way as you would use any other type. Just specify the enum
type in the switch
statement and use the enum
constant values as the case
labels.