This video tutorial demonstrates how to use the Java switch statement with the String data type, which is new to Java 1.7. In Java 1.5 and 1.6, you would use an enumeration instead. This Java programming training video also shows you how to create an enumeration variable, using it in conjunction with a switch statement as well.
Using Java 1.5 and Java 1.6 Enumeration:
public class MySwitchTest {
enum Month {JANUARY, FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST};
public static void main(String[] args) {
Month currMonth = Month.APRIL;
switch (currMonth) {
case MARCH:
case APRIL:
case MAY:
System.out.println("Spring is in the air!");
break;
case JUNE:
case JULY:
case AUGUST:
System.out.println("Summer is here...");
break;
default:
System.out.println("Neither spring nor summer!");
}
}
}
Switch Statement using String in Java 1.7
public class MySwitchTestEnum {
enum Month {JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE};
public static void main(String[] args) {
Month currMonth = Month.APRIL;
switch(currMonth){
case JANUARY:
case FEBRUARY:
System.out.println("Winter is here...");
break;
case MARCH:
case APRIL:
case MAY:
System.out.println("Spring is in the air...");
break;
default:
System.out.println("Not winter or spring...");
}
}
}
Please Share This Knowledge With Others!