A common structure in many programming languages is the "select-case"
statement. This kind of statement is a lot like a
multi-sided selection and in most cases, can be a lot more powerful
and efficient than a multi-sided selection.
Java's version of a "case" statement is the
switch statement. In this lesson you'll learn to
use the switch statement, and why it might
be a better choice than the mulit-selection structure.
The switch statement examines one value (e.g. a
variable or expression result) and performs an action or actions
based on that value. The switch statement can only examine values
that are Strings, or that are castable into an int (int, byte,
short, and char). You can't use a switch
with any other data type.
The general format of a switch statement is:
switch (expression) {
case value1:
// execute if expression == value1
break;
case value2:
// execute if expression == value2
break;
case value3:
// execute if expression == value3
break;
default:
// execute if none of the above match
}
Pay close attention to the syntax of this statement:
The variable you are testing must go after
"switch" in brackets.
Each case statement ends with a colon.
Don't use braces if a case contains more
than one statement.
"default:" is optional and can be used
when none of the cases apply (like an
else in a multi-sided if)
You'll also notice the break;
statement in each of the case blocks.
These are optional, but most of the time you would
want to keep them.
To see why, run this program:
public class TrySwitch1 {
public static void main(String[] args) {
int number = 2;
switch (number) {
case 1:
System.out.println("one");
case 2:
System.out.println("two");
case 3:
System.out.println("three");
default:
System.out.println("too many!");
}
}
}
What output do you expect? What output do you get?
This can actually come in handy:
public class TrySwitch2 {
public static void main(String[] args) {
int number = 5;
switch (number) {
case 1:
System.out.println("only one");
break;
case 2:
case 3:
System.out.println("a few");
break;
case 4:
case 5:
case 6:
System.out.println("a handful");
break;
default:
System.out.println("too many!");
}
}
}
Try re-running this program with the values 1, 3, and 9 for
the variable number.
Prior to Java 7, you could only use a switch statement with any data type
that could be implicitly cast into an int (byte, short, char, and int).
In the Java 7 release, the switch statement was given support for String
objects:
public class FindProvCode {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter full province/territory name:")
String province = in.nextLine();
String provAbbrev = "";
switch (province.toLowerCase()) {
case "alberta":
provAbbrev = "AB";
break;
case "british columbia":
provAbbrev = "BC";
break;
case "manitoba":
provAbbrev = "MB";
break;
case "new brunswick":
provAbbrev = "NB";
break;
case "newfoundland labrador":
provAbbrev = "NL";
break;
case "nova scotia":
provAbbrev = "NS";
break;
case "northwest territories":
provAbbrev = "NT";
break;
case "nunavut":
provAbbrev = "NU";
break;
case "ontario":
provAbbrev = "ON";
break;
case "prince edward island":
case "pei":
provAbbrev = "PE";
break;
case "quebec":
provAbbrev = "QC";
break;
case "saskatchewan":
provAbbrev = "SK";
break;
case "yukon":
provAbbrev = "YT";
break;
}
System.out.println("Official abbreviation for " +
province + ": " + provAbbrev);
}
}
Exercises
1. Rewrite the following selection statement as a
switch statement:
import java.util.Scanner;
public class IfToSwitch {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
System.out.println("Enter the shipment status:");
int status = keysIn.nextInt();
String action = "";
if (status == 1) {
action = "Phone vendor and request delivery.";
} else if (status == 2) {
action = "Phone customer and warn of late shipment.";
} else if (status == 3) {
action = "Prepare shipping labels.";
} else if (status == 4) {
action = "Order additional product from vendor.";
} else {
action = "Error: Invalid status code.";
}
System.out.println(action);
}
}
2. A restaurant has different specials, depending on
the day of the week. Write a program using a switch statement that requests a
number from 1 to 7 representing the day of the week (Sunday is 1) and
displays the daily special according to the table below:
Day
Special
Sunday
Roast Chicken
Monday
Lasagne
Tuesday
Pizza
Wednesday
Hot Wings
Thursday
Roast Chicken
Friday
Fish and Chips
Saturday
Pizza
3. A program is needed to calculate delivery costs to various
provinces and territories in Canada. The table below describes how the
delivery costs are calculated:
Provinces
Abbreviation
Delivery Cost
Maritime Provinces
Nova Scotia, New Brunswick, PEI
NS, NB,
PE
29.95
Newfoundland & Labrador
NL
34.95
Central Provinces
Quebec, Ontario
QC, ON
24.95
Prairie Provinces
Manitoba, Saskatchewan
MB, SK
29.95
Western Provinces
Alberta, British Columbia
AB, BC
37.95
Territories
Nunavut, Northwest Territories, Yukon Territory
NU, NT,
YT
39.95
The user will enter the province's official code abbreviation and the
program should display the correct delivery cost.