Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using The switch Statement in Java http://www.chankok.com/java-use-the-switch-statement/
public class EnumSwitchStatementExample {
public static void main(String[] args) {
// Using enum Type Argument in The switch Statement
Day day = Day.TUESDAY;
switch (day) {
case MONDAY:
case TUESDAY:
case WEDNESDAY:
case THURSDAY:
case FRIDAY:
System.out.println(day + " is weekday");
break;
case SATURDAY:
case SUNDAY:
System.out.println(day + " is weekend");
break;
default:
System.out.println(day + " is an invalid day");
}
}
}
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, SATURDAY, SUNDAY
}
public class IntSwitchStatementExample {
public static void main(String[] args) {
// Using int Type Argument in The switch Statement
int monthNumber = 6;
switch (monthNumber) {
case 1:
System.out.println("Month number " + monthNumber + " is January");
break;
case 2:
System.out.println("Month number " + monthNumber + " is February");
break;
case 3:
System.out.println("Month number " + monthNumber + " is March");
break;
case 4:
System.out.println("Month number " + monthNumber + " is April");
break;
case 5:
System.out.println("Month number " + monthNumber + " is May");
break;
case 6:
System.out.println("Month number " + monthNumber + " is June");
break;
case 7:
System.out.println("Month number " + monthNumber + " is July");
break;
case 8:
System.out.println("Month number " + monthNumber + " is August");
break;
case 9:
System.out.println("Month number " + monthNumber + " is September");
break;
case 10:
System.out.println("Month number " + monthNumber + " is October");
break;
case 11:
System.out.println("Month number " + monthNumber + " is November");
break;
case 12:
System.out.println("Month number " + monthNumber + " is December");
break;
default:
System.out.println("Month number " + monthNumber + " is an invalid month");
}
}
}
public class StringSwitchStatementExample {
public static void main(String[] args) {
// Using String Type Argument in The switch Statement
String day = "Saturday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
System.out.println(day + " is weekday");
break;
case "Saturday":
case "Sunday":
System.out.println(day + " is weekend");
break;
default:
System.out.println(day + " is an invalid day");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment