- How to use Java Enum in Switch Case Statement — Exampel Tutorial
- Enum in Switch case — Java
- How to use an enum with switch case in Java?
- Enum with switch case
- Example
- Output
- Can you use a switch statement around an enum in Java?
- Using enumeration with switch
- Syntax
- Example
- Output
- A Java enum switch/case statement example
- A Java enum switch statement example
- Discussion
- Summary
- Related Java enum content
How to use Java Enum in Switch Case Statement — Exampel Tutorial
Yesterday, someone ask me Can we use Java Enum in Switch case? Obviously, he was learning Enum and not aware that How powerful Enum in Java is. Yes, You can use Enum in Switch case statement in Java like int primitive. If you are familiar with enum int pattern, where integers represent enum values prior to Java 5 then you already knows how to use the Switch case with Enum. Using Java Enum in the Switch case is pretty straightforward, Just use Enum reference variable in Switch and Enum constants or instances in CASE statement. In this Java tutorial we will see one example of How to use Enum in Switch statement in Java.
By the way Enum is feature rich in Java, Enum can implement interface in Java, Enum can override method in Java, Enum can have constructor in Java and Enum is full functional Type like class or interface.
Programmers use Enum with different ways. One of the best example of Enum in Java is replace enum int pattern and enum String pattern. You can also use Enum to write Thread-safe Singleton in Java.
Enum in Switch case — Java
In this example of using Enum in Switch case, we have created a Days of Week Enum which represents all days e.g. Monday, Tuesday etc. Then we get all Enum instances in an array using Enum.values() method and by using advanced for loop of Java 5, we loop through each of that Enum instance.
By the way, you can also use String in Switch case from Java7 onwards. Similarly, you can also convert Enum to String in Java.
In the body of for loop, we have created a switch case statement using Enum in Java. Which switch on current Enum instance and every CASE statement is individual Enum instance e.g. DAY.MONDAY or DAY.TUESDAY .
Since you have declared Enum in the same class you can use their instance without calling them with class name e.g. MONDAY . Here is a complete code example of using Enum in Switch case in Java :
/**
*
* Java program to demonstrate how to use Enum in Switch case statement.
* Enum can be used in switch block similar to primitive int or enum int pattern.
* Enum can also be used in CASE statement to take appropriate action based upon
* Enum instance.
*
* @author Javin
*/
public class EnumInSwitch
public enum Day
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY ;
>
public static void main ( String args [])
Day [] daysOfWeek = Day. values () ;
for ( Day today : daysOfWeek )
//Using Enum in Switch case statement
switch ( today ) <
case MONDAY:
System. err . println ( «Today is Monday learn example of How to use Java Enum in Switch» ) ;
break ;
case TUESDAY:
System. err . println ( «Tuesday, apply Enum in Switch just link primitive int» ) ;
break ;
case WEDNESDAY:
System. err . println ( «Wednesday, I confirm Java Enum can be used in Switch case» ) ;
break ;
case THURSDAY:
System. err . println ( «Thursday, Java Enum values() method return all enum in an array» ) ;
break ;
case FRIDAY:
System. err . println ( «Friday, Enum can also be used in case statement» ) ;
break ;
case SATURDAY:
System. err . println ( «Saturday, Enum in Java are compile time constant» ) ;
break ;
case SUNDAY:
System. err . println ( «Sunday, Using Enum in Switch is very easy» ) ;
break ;
Output:
Today is Monday learn example of using Java Enum in Switch
Tuesday, apply Enum in Switch just link primitive int
Wednesday, I confirm Java Enum can be used in Switch case
Thursday, Java Enum values () method return all enum in an array
Friday, Enum can also be used in case statement
Saturday, Enum in Java are compile time constant
Sunday, Using Enum in Switch is very easy
That’s all on How to use Enum in Switch case in Java. Its indeed very easy and after trying it one time , you will be familiar with that. Just get yourself familiar with Enum API and some useful methods like the name(), cardinal(), values() etc, which will help you to get most of Java Enum apart from just using Enum in Switch case.
- Top 15 Java Enum Interview Questions with Answers (see here)
- Difference between RegularEnumSet and JumboEnumSet in Java (read here)
- String to Enum in Java with Example (check here)
- Can we use Enum in Switch Statement in Java (Yes)
- How to use valueOf method of Enum (check here)
- What Every Java Programmer Should know about Enum (click here)
- 10 points about Enum in Java (see here)
- How to loop over Enum constants in Java (example)
- Learn how to use Enum in Java with a Simple Example (check here)
- Java tip to convert Enum to String in Java (see tip)
- Can Enum have Constructor in Java (learn here)
- 10 Courses to learn Java for Beginners (courses)
Thanks for reading this article so far. If you find this article useful then please share it on Facebook, Twitter, and LinkedIn.
How to use an enum with switch case in Java?
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values.
Enum with switch case
Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below −
enum Scoters < //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Scoters(int price) < this.price = price; >//Static method to display the price public static void getPrice(int model) < Scoters constants[] = Scoters.values(); System.out.println("Price of: "+constants[model]+" is "+constants[model].price); >>
Following Java program retrieves the prices of all the vehicles using switch case.
Example
public class EnumExample < Scoters sc; public EnumExample(Scoters sc) < this.sc = sc; >public void displayPrice() < switch (sc) < case Activa125: Scoters.getPrice(0); break; case Activa5G: Scoters.getPrice(1); break; case Access125: Scoters.getPrice(2); break; case Vespa: Scoters.getPrice(3); break; case TVSJupiter: Scoters.getPrice(4); break; default: System.out.println("Model not found"); break; >> public static void main(String args[]) < EnumExample activa125 = new EnumExample(Scoters.ACTIVA125); activa125.displayPrice(); EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G); activa5G.displayPrice(); EnumExample access125 = new EnumExample(Scoters.ACCESS125); access125.displayPrice(); EnumExample vespa = new EnumExample(Scoters.VESPA); vespa.displayPrice(); EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER); tvsJupiter.displayPrice(); >>
Output
Price of: ACTIVA125 is 80000 Price of: ACTIVA5G is 70000 Price of: ACCESS125 is 75000 Price of: VESPA is 90000 Price of: TVSJUPITER is 75000
Can you use a switch statement around an enum in Java?
Enumeration (enum) in Java is a datatype which stores a set of constant values. You can use enumerations to store fixed values such as days in a week, months in a year etc.
You can also define an enumeration with custom values to the constants declared. But you need to have an instance variable, a constructor and getter method to return values.
Using enumeration with switch
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case
Syntax
With the switch statement you can use int, char or, enum types. Usage of any other types generates a compile time error.
Example
Let us create an enum with 5 constants representing models of 5 different scoters with their prices as values, as shown below −
enum Scoters < //Constants with values ACTIVA125(80000), ACTIVA5G(70000), ACCESS125(75000), VESPA(90000), TVSJUPITER(75000); //Instance variable private int price; //Constructor to initialize the instance variable Scoters(int price) < this.price = price; >//Static method to display the price public static void getPrice(int model) < Scoters constants[] = Scoters.values(); System.out.println("Price of: "+constants[model]+" is "+constants[model].price); >>
Following Java program retrieves the prices of all the vehicles using switch case.
public class EnumExample < Scoters sc; public EnumExample(Scoters sc) < this.sc = sc; >public void displayPrice() < switch (sc) < case Activa125: Scoters.getPrice(0); break; case Activa5G: Scoters.getPrice(1); break; case Access125: Scoters.getPrice(2); break; case Vespa: Scoters.getPrice(3); break; case TVSJupiter: Scoters.getPrice(4); break; default: System.out.println("Model not found"); break; >> public static void main(String args[]) < EnumExample activa125 = new EnumExample(Scoters.ACTIVA125); activa125.displayPrice(); EnumExample activa5G = new EnumExample(Scoters.ACTIVA5G); activa5G.displayPrice(); EnumExample access125 = new EnumExample(Scoters.ACCESS125); access125.displayPrice(); EnumExample vespa = new EnumExample(Scoters.VESPA); vespa.displayPrice(); EnumExample tvsJupiter = new EnumExample(Scoters.TVSJUPITER); tvsJupiter.displayPrice(); >>
Output
Price of: ACTIVA125 is 80000 Price of: ACTIVA5G is 70000 Price of: ACCESS125 is 75000 Price of: VESPA is 90000 Price of: TVSJUPITER is 75000
A Java enum switch/case statement example
Java enum FAQ: Can you share a Java enum switch example, i.e., how to use an enum with a Java switch statement?
In my earlier Java enum examples tutorial, I demonstrated how to declare a simple Java enum , and then how to use an enum with a variety of Java constructs, including a Java switch statement, a for loop, and an if/then statement.
In this enum tutorial, I want to just focus on using an enum in a switch statement. Hopefully this enum/switch example adds a little more complexity to my earlier examples.
A Java enum switch statement example
In this enum/switch example, I first declare an enum type that looks like this:
Then in the main portion of the program, I refer to that enum , both in my main method, and in the “print” method that I call from the main method.
Let’s take a look at the Java source code for my enum example, and then I’ll describe it afterwards:
/** * A Java enum switch statement (switch/case) example. * @author alvin alexander, https://alvinalexander.com */ public class JavaEnumSwitchCaseExample < public static void main(String[] args) < // loop through the enum values, calling the // print method once for each value for (Day d: Day.values()) < printTodaysThought(d); >> // a method that prints a String corresponding to the day value // that is passed in. public static void printTodaysThought(Day theDay) < switch (theDay) < case MONDAY: case TUESDAY: case WEDNESDAY: case THURSDAY: System.out.println("Working for the man :)"); break; case FRIDAY: System.out.println("TGIF "); break; case SATURDAY: case SUNDAY: System.out.println("Ahh, the weekend . "); break; default: System.out.println("What day is it?");; >> > /** * Our «Day» enum type */ enum Day
When you compile and run this code, the output looks like this:
Ahh, the weekend . Working for the man :) Working for the man :) Working for the man :) Working for the man :) TGIF Ahh, the weekend .
The output is in this order because the enum begins on SUNDAY , and goes in order from there until SATURDAY .
Discussion
As with any Java program, the flow of control starts in the main method. Inside main I jump right in with this for loop:
This “enum for loop” iterates through all the values in the Day enum, using the values method that comes with Java’s enum type. That’s really the only “trick” in this code; the rest of it is a standard Java 5 for loop, and it calls the printTodaysThought method once for each constant in the Day enum.
The printTodaysThought method takes one Day value ( theDay ), and compares that variable against the constants that are shown in the switch statement. For the values MONDAY through THURSDAY I print one String; for FRIDAY I print a different string; and SATURDAY and SUNDAY print their own string. If a calling program manages to somehow call this method with a different Day value — something which should be really hard to do, unless I add a new value to the Day enum — flow of control will fall down to the default expression.
Summary
I hope this Java enum switch statement example has been helpful. Between my original Java enum tutorial and this tutorial, I hope it helps to see at least two examples of how to use a custom enum type with a switch statement (sometimes called a case statement).
Related Java enum content
As I finish up my Java enum series, here’s a collection of the Java enum tutorials I’ve written. Again, I hope you find them helpful: