You can now use an enum type in a "switch" statement, Earlier the switch expression had to be an int type.
Sun's Javac says -"enum switch case label must be the unqualified name of an enumeration constant.
So let's understand this with a simple example:
package com.doyou.know;
public class EnumInSwitch {
public static enum Month { Jan, Feb, March }
public void printMonth(Month month) {
switch(month) {
case(Month.Jan): //Wrong: can not use parenthesis
System.out.println("January month..");
case Month.Feb: //Wrong Too: Enum reference can not be qualified
System.out.println("February month..");
case March: //RIGHT : this is how you do it ...
System.out.println("March month...");
}
}
public static void main(String[] args) {
new EnumInSwitch().printMonth(Month.March);
}
}
To summarize:
• In case statement the enum must be used without brackets.
• In case only the unqualified enum name (Jan, Feb, March) must be used.
Sunday 28 September 2008
Do you know? Enum in Switch statements
Subscribe to:
Posts (Atom)