

The printTodaysThought method takes one Day value ( theDay), and compares that variable against the constants that are shown in the switch statement.
Case in java code#
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. This “enum for loop” iterates through all the values in the Day enum, using the values method that comes with Java’s enum type.

Inside main I jump right in with this for loop: DiscussionĪs with any Java program, the flow of control starts in the main method. The output is in this order because the enum begins on SUNDAY, and goes in order from there until SATURDAY. When you compile and run this code, the output looks like this:

Public static void printTodaysThought(Day theDay)Ĭase THURSDAY: ("Working for the man :)") Ĭase FRIDAY: ("TGIF ") Ĭase SUNDAY: ("Ahh, the weekend. a method that prints a String corresponding to the day value loop through the enum values, calling the * A Java enum switch statement (switch/case) example. Let’s take a look at the Java source code for my enum example, and then I’ll describe it afterwards: 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. SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY In this enum/switch example, I first declare an enum type that looks like this: Hopefully this enum/switch example adds a little more complexity to my earlier examples. In this enum tutorial, I want to just focus on using an enum in a switch statement.
Case in java how to#
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. Java enum FAQ: Can you share a Java enum switch example, i.e., how to use an enum with a Java switch statement?
