Javatpoint Logo
Javatpoint Logo

Switch case with enum in Java

enum keyword

Java has a special sort of data type called an Enum, which is typically a collection (set) of constants. To be more precise, a Java Enum type is a special form of Java class. A constant, a procedure, etc. may be contained in an Enum. It is possible to use an Enum keyword with an if statement, switch statement, iteration, etc.

  • By default, enum constants were public, static, and final.
  • Using dot syntax, enum constants are accessible.
  • Along with constants, an enum class may also contain attributes and methods.
  • Enum classes cannot inherit other classes and you can't create objects of them.
  • Enum classes are limited to interface implementation.

File name: EnumExample.jav

Output:

MAY

switch keyword

When a user has a lot of options and wishes to complete a separate task for each decision, the Switch statement is useful. The Switch statement makes it possible to compare the value of a variable to a list of potential values. Each value has a distinct case. With a break statement, a switch Case statement is frequently used, though it is not required.

File name: SwitchExample.java

Output:

The number is other than 1, 2 or 3

The enum keyword is also compatible with the Switch statement. Enum can be used similarly to an int primitive in a Java Switch case statement. The following examples show how an Enum with something like a Switch statement functions.

Example 1:

When an enum is used outside of the main class, a switch statement is used.

File name: EnumSwitch.java

Output:

Hurray ! You have chosen Apache!

The aforementioned example demonstrates how, when Enum is specified outside the main class, the Enum keyword and Switch case instructions function.

Example 2: When using an Enum with a Switch statement, make sure the Enum is in the main class.

File name: EnumSwitch1.java

Output:

Hurray ! You have chosen Apache!

The aforementioned illustration shows how, if Enum is declared inside the main class, the Enum keyword works in conjunction using Switch case statements.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA