How to use Enum in Switch?

Enums introduced in Java 5.0 (Read: New features in Java 5.0) allows switching to be done based on the enums values. It is one of the greatest new features introduced from the version 5.0. Prior to Java 1.4, switch only worked with int, short, char, and byte values. However, since enums have a finite set of values, Java 1.5 adds switch support for the enum. Some of the advantages of using enums are it is strongly typed, Comparing enums is faster, you can use == instead equals() and Enums can implement interfaces, methods and functions.

also read:

Here’s an example of using an enum in a switch statement.

public class EnumSwitcher {
public enum Grade { A, B, C, D, F, INCOMPLETE };

public static void main(String[] args) {
Grade examGrade	= Grade.C;

System.out.println('Switching based on the enums values.');
switch (examGrade) {
	case A:
		System.out.println('The students grade is ' + Grade.A);
	case B: // fall through to C
	case C:
		System.out.println('The students grade is ' + Grade.C);
	case D: // fall through to F
	case F:
		System.out.println('The students grade is ' + Grade.F);
		System.out.println('The students grade is ' + Grade.INCOMPLETE);
		System.out.println('The students grade is unknown.');


Given below is the output of the above program.

Switching based on the enums values.

The students grade is C

As you can see from the above example, there is nothing special in using an enum with a switch case statement.



About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind