Switch Statement
Submitted by GeePee on Saturday, June 13, 2015 - 22:32.
Introduction:
Welcome to a tutorial page on how to use a Switch statement within Java.
What is a Switch statement?
A Switch statement is used to check multiple cases or conditions for a particular instance. In Java 7, switch statements can be used for Strings and Integers whereas older versions of Java can only use Integers in a switch statement.
When is a Switch statement used?
A switch statement is very similar to a If and Else If statement except using a switch statement is much cleaner, less complex and you do not have to state the variable to check each time you want to check it - this does in-turn mean that you can only use one variable per switch statement.
Examples:
Setting up the methods to be created as examples:
Here is an integer example from the official Java Documents to convert the month integer to a string...
and here is a Java 7 example of turning a string in to an integer...
Which gives the combined output:
- switch (month) {
- case 1: futureMonths = "January";
- break;
- case 2: futureMonths = "February";
- break;
- case 3: futureMonths = "March";
- break;
- case 4: futureMonths = "April";
- break;
- case 5: futureMonths = "May";
- break;
- case 6: futureMonths = "June";
- break;
- case 7: futureMonths = "July";
- break;
- case 8: futureMonths = "August";
- break;
- case 9: futureMonths = "September";
- break;
- case 10: futureMonths = "October";
- break;
- case 11: futureMonths = "November";
- break;
- case 12: futureMonths = "December";
- break;
- default: break;
- }
- return futureMonths;
- }
- int monthNumber = 0;
- if (month == null) {
- return monthNumber;
- }
- switch (month.toLowerCase()) {
- case "january":
- monthNumber = 1;
- break;
- case "february":
- monthNumber = 2;
- break;
- case "march":
- monthNumber = 3;
- break;
- case "april":
- monthNumber = 4;
- break;
- case "may":
- monthNumber = 5;
- break;
- case "june":
- monthNumber = 6;
- break;
- case "july":
- monthNumber = 7;
- break;
- case "august":
- monthNumber = 8;
- break;
- case "september":
- monthNumber = 9;
- break;
- case "october":
- monthNumber = 10;
- break;
- case "november":
- monthNumber = 11;
- break;
- case "december":
- monthNumber = 12;
- break;
- default:
- monthNumber = 0;
- break;
- }
- return monthNumber;
- }
2
February
Finished!Add new comment
- 74 views