Switch Statements
There is a second type of conditional statement in Java called a switch statement. These statements can be used as a shortcut over if statements when checking the value of variables or expressions.
Switch statement syntax
Here is the syntax of a switch statement:
switch (expression)
{
case val1:
//first set of statements
break;
case val2:
//second set of statements
break;
...
default:
//last set of statements
}Here, expression is either an expression or variable that has type char, int, or String (in more recent versions of Java).
Inside the statement, val1, val2, etc. are possible values for expression. If
expression equals val1, then we execute the statements inside the val1 case. If
expression equals val2, then we execute the statements inside the val2 case. We
can have as many cases as we want (as denoted by the …).
The default case is executed if expression does not evaluate to any of the case values. This default case is optional.
The “break” statements at the end of each case mean that we will leave the switch statement at
the end of a case. They are also optional, but if we leave them out then we will continue on to
the statements in the next case (WITHOUT checking the case value). We will see an example of
this in the next sections.
Switch statement example with ints
Here is an example that gets a month number (1-12) from the user and prints the corresponding month name:
Scanner s = new Scanner();
System.out.print("Enter month number (1-12): ");
int monthNum = s.nextInt();
String monthName;
switch(monthNum)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Invalid month";
break;
}
System.out.println(monthName);For example, if we ran our code fragment and entered 4 at the prompt, then the program would print “April”. If we ran it again and entered 13, then the program
would print “Invalid month”.
Equivalent if…else if statement
We can always rewrite a switch statement using an if…else if statement that has an else if branch corresponding to each case in the switch. Here is our month name example repeated with an if…else if statement:
Scanner s = new Scanner();
System.out.print("Enter month number (1-12): ");
int monthNum = s.nextInt();
String monthName;
if (monthNum == 1)
{
monthName = "January";
}
else if (monthNum == 2)
{
monthName = "February";
}
else if (monthNum == 3)
{
monthName = "March";
}
else if (monthNum == 4)
{
monthName = "April";
}
else if (monthNum == 5)
{
monthName = "May";
}
else if (monthNum == 6)
{
monthName = "June";
}
else if (monthNum == 7)
{
monthName = "July";
}
else if (monthNum == 8)
{
monthName = "August";
}
else if (monthNum == 9)
{
monthName = "September";
}
else if (monthNum == 10)
{
monthName = "October";
}
else if (monthNum == 11)
{
monthName = "November";
}
else if (monthNum == 12)
{
monthName = "December";
}
else
{
monthName = "Invalid month";
}
System.out.println(monthName);However, the structure of an if…else if statement can require more code that a switch statement (the expression we are evaluating must be retyped in each condition, and we often need to include brackets around each case), so switch statements are a convenient shortcut.
Switch statement example with chars
Here is an example that uses a switch statement to print out comments about a given letter grade:
Scanner s = new Scanner(System.in);
System.out.print("Enter your letter grade: ");
//this technique converts the string to a char
//by getting the first character from the input string
char grade = (s.nextLine()).charAt(0);
switch (grade)
{
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
case 'D':
System.out.println("Poor");
break;
case 'F':
System.out.println("Failure");
break;
default:
System.out.println("Invalid grade");
break;
}Depending on what grade the user entered, exactly one of the case statements will be printed.
Switch statement example without breaks
To see what happens when we leave some break statements out, suppose we want to repeat the letter grade example, but just print out whether the user passed (A, B, or C) or failed (D or F). Here’s what we would do:
switch (grade)
{
case 'A':
case 'B':
case 'C':
System.out.println("Pass");
break;
case 'D':
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid grade");
break;
}If the user enters A, for example, then we will first go to case A in the switch statement.
Since there is no break statement, we will go directly to case B (even though the grade entered
doesn’t match that case). There is not a break statement in B either, so we will go to case C.
There we will print “Pass” (which we should for an A grade) and break out of the switch
statement.
Switch statement example with Strings
In more recent versions of Java, we can also use a switch statement to evaluate a String variable or expression. Here is an example that gets a month name from the user and prints out the corresponding month number:
Scanner s = new Scanner(System.in);
System.out.print("Enter a month name: ");
String monthName = s.nextLine();
int monthNum;
switch (monthName)
{
case "January":
monthNum = 1;
break;
case "February":
monthNum = 2;
break;
case "March":
monthNum = 3;
break;
case "April":
monthNum = 4;
break;
case "May":
monthNum = 5;
break;
case "June":
monthNum = 6;
break;
case "July":
monthNum = 7;
break;
case "August":
monthNum = 8;
break;
case "September":
monthNum = 9;
break;
case "October":
monthNum = 10;
break;
case "November":
monthNum = 11;
break;
case "December":
monthNum = 12;
break;
default:
monthNum = -1;
break;
}
if (monthNum != -1)
{
System.out.printf("Month number: %d%n", monthNum);
}
else
{
//monthNum will be -1 if we went in our "default" switch case above
System.out.println("Invalid month name");
}The above example will only work correctly if the user types the month name using the format in our cases (capital first letter, lowercase subsequent letters). A trick to repeating this example WITHOUT checking for a specific format is to first convert the input month to lowercase, and then to change our cases to be in lowercase format:
Scanner s = new Scanner(System.in);
System.out.print("Enter a month name: ");
String monthName = s.nextLine();
int monthNum;
switch (monthName.toLowerCase())
{
case "january":
monthNum = 1;
break;
case "february":
monthNum = 2;
break;
case "march":
monthNum = 3;
break;
case "april":
monthNum = 4;
break;
case "may":
monthNum = 5;
break;
case "june":
monthNum = 6;
break;
case "july":
monthNum = 7;
break;
case "august":
monthNum = 8;
break;
case "september":
monthNum = 9;
break;
case "october":
monthNum = 10;
break;
case "november":
monthNum = 11;
break;
case "december":
monthNum = 12;
break;
default:
monthNum = -1;
break;
}
if (monthNum != -1)
{
System.out.printf("Month number: %d%n", monthNum);
}
else
{
//monthNum will be -1 if we went in our "default" switch case above
System.out.println("Invalid month name");
}Now, whether the user enters “September”, “september”, or “SePTembER”, the program will always print 9 as the month number.