Header Ads

How To Work With Java Enum In Switch Argument??

In my last post (http://www.mydigitalvoice.in/2013/05/how-to-get-values-from-enum-in-java.html) I have said how to get values from enum. This post talks about how to work with enum inside switch statement.

Generally we use if when we need to compare small number of (say 2-3) variables,but for big number of condition check it is always better to go for switch statement.
Until java 1.4 version(java4) switch statement used to take byte,short,char and int as argument.
From java1.5(java 5 or tiger) edition switch supports corresponding wrapper classes and enum types.

Java 1.4

java 1.5

java 1.7

byte

Byte

String

short

Short



char

Character



int

Interger





enum

So after java 1.5 onwards,enum can be passed as a type as an argument to switch statement
lets check out one example:
enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Month mon=Month.MAR;
//create switch statement
  switch(mon)
  {
  case JAN : System.out.println("1st Month");break;
  case FEB : System.out.println("2nd Month");break;
  case MAR : System.out.println("3rd Month");break;
  
  }

 }

}

output:
3rd Month
we can pass enum type as argument to switch statement, but every case label should be Valid enum contant. Otherwise we will get compile time error.
enum Month
{
 JAN,FEB,MAR;
//declare enum
}
public class enumTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Month mon=Month.MAR;
//create switch statement
  switch(mon)
  {
  case JAN : System.out.println("1st Month");break;
  case FEB : System.out.println("2nd Month");break;
  case MAR : System.out.println("3rd Month");break;
  case APR : System.out.println("4th Month");break;
  }

 }

}

Output:
Compilation error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
APR cannot be resolved or is not a field
^
at enumTest.main(enumTest.java:20)
Powered by Blogger.