Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc.
- enum constants are public, static, and final by default.
- enum constants are accessed using dot syntax.
- An enum class can have attributes and methods, in addition to constants.
- You cannot create objects of an enum class, and it cannot extend other classes.
- An enum class can only implement interfaces.
The Switch statement is helpful when a user has a number of choices and wants to perform a different task for each choice. The Switch statement allows the testing of a variable for equality against a list of values. Each value is known as a case. A switch Case statement is generally used with a break statement but it is optional.
Other than 10, 20 or 30
We can use also use Enum keyword with Switch statement. We can use Enum in Switch case statement in Java like int primitive. Below are some examples to show working of Enum with Switch statement.
Example 1: Use of Enum with Switch statement when Enum is outside the main class
You choose AUDI !
In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared outside the main class.
Example 2: Use of Enum with Switch statement when Enum is within the main class
In the above example, we show how the Enum keyword works along with Switch case statements when Enum is declared within main class.