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, and iteration, etc.
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 Enum keyword works along with Switch case statements when Enum is declared outside main class.
Example 2: Use of Enum with Switch statement when Enum is within main class
In the above example, we show how Enum keyword works along with Switch case statements when Enum is declared within main class.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.