public class Java7Feature1 {
private static String color = "BLUE";
private enum Color {
RED, GREEN
};
public static void main(String[] args) {
// Pre Java 5
if (color.equals("RED")) {
System.out.println("Color is Red");
} else if (color.equals("GREEN")) {
System.out.println("Color is Green");
} else {
System.out.println("Color not found");
}
// Java 5 enum. try/catch is required for colours other than RED and GREEN
try {
switch (Color.valueOf(color)) {
case RED:
System.out.println("Color is Red");
break;
case GREEN:
System.out.println("Color is Green");
}
} catch (IllegalArgumentException e) {
System.out.println("Color not found");
}
// Java 7 String in switch statement for simplicity & better readability
//JDK 7 switch performs better than if-else
//using types with enums is only useful when it serves a meaningful purpose
//the value for color could come from database, and string in switch is handy for this
switch (color) {
case "RED":
System.out.println("Color is Red");
break;
case "GREEN":
System.out.println("Color is Green");
break;
default:
System.out.println("Color not found");
}
}
}