Comparing a Number of Mutually Exclusive options - The switch Statement

Contact Us or call 1-877-932-8228
Comparing a Number of Mutually Exclusive options - The switch Statement

Comparing a Number of Mutually Exclusive options - The switch Statement

The switch Statement

A switch expression (usually a variable) is compared against a number of possible values. It is used when the options are each a single, constant value that is exactly comparable (called a case).

The switch expression must be a byte, char, short, or int. Cases may only be byte, char, short, or int values; in addition, their magnitude must be within the range of the switch expression data type and cannot be used with floating-point datatypes or long and cannot compare an option that is a range of values, unless it can be stated as a list of possible values, each treated as a separate case.

Cases are listed under the switch control statement, within curly braces, using the case keyword. Once a match is found, all executable statements below that point are executed, including those belonging to later cases; this allows stacking of multiple cases that use the same code.

The break; statement is used to jump out of the switch block, thus skipping executable steps that are not desired. The default case keyword catches all cases not matched above - note that the default case does not need to be the last thing in the switch. Note that technically speaking, the cases are labeled lines; the switch jumps to the first label whose value matches the switch expression.

Usage

switch ( expression ) {
	case constant1: 
		statements;
		break;
	case constant2:
		statements;
		break;
	. . .
	case constant3:
	case constant4:
		MeansTheSameAs3:
		statements;
		break;
	. . .
	[default:
		statements;]
}

switch Statement Examples

 

Code Sample:

Java-Control/Demos/Switch1.java
import util.KeyboardReader;

public class Switch1 {
  public static void main(String[] args) {
    char c = 'X';
    c = KeyboardReader.getPromptedChar("Enter a letter a - d: ");
    switch (c) {
      case 'a':
      case 'A': System.out.println("A is for Aardvark");
                break;
      case 'b':
      case 'B': System.out.println("B is for Baboon");
                break;
      case 'c':
      case 'C': System.out.println("C is for Cat");
                break;
      case 'd':
      case 'D': System.out.println("D is for Dog");
                break;
      default:  System.out.println("Not a valid choice");
    }
  }
}

Three points to note:

  • Stacking of cases for uppercase and lowercase letters allows both possibilities.
  • break; statements used to separate code for different cases.
  • default: clause used to catch all other cases not explicitly handled.

Here is a revised version that moves the default to the top, so that a bad entry is flagged with an error message, but then treated as an 'A' - note that there is no break below the default case.

Code Sample:

Java-Control/Demos/Switch2.java
import util.KeyboardReader;

public class Switch2 {
  public static void main(String[] args) {
    char c = 'X';
    c = KeyboardReader.getPromptedChar("Enter a letter a - d: ");
    switch (c) {
      default:  System.out.println("Not a valid choice - assuming 'A'");
      case 'a':
      case 'A': System.out.println("A is for Aardvark");
                break;
      case 'b':
      case 'B': System.out.println("B is for Baboon");
                break;
      case 'c':
      case 'C': System.out.println("C is for Cat");
                break;
      case 'd':
      case 'D': System.out.println("D is for Dog");
                break;
    }
  }
}

Another example is taking advantage of the "fall-though" behavior without a break statement.

Code Sample:

Java-Control/Demos/Christmas.java
import util.KeyboardReader;

public class Christmas {
  public static void main(String[] args) {
    int day = KeyboardReader.getPromptedInt("What day of Christmas? ");
    System.out.println(
        "On the " + day + " day of Christmas, my true love gave to me:");
    switch (day) {
      case 12: System.out.println("Twelve drummers drumming,"); 
      case 11: System.out.println("Eleven pipers piping,"); 
      case 10: System.out.println("Ten lords a-leaping,"); 
      case 9: System.out.println("Nine ladies dancing,"); 
      case 8: System.out.println("Eight maids a-milking,"); 
      case 7: System.out.println("Seven swans a-swimming,"); 
      case 6: System.out.println("Six geese a-laying,"); 
      case 5: System.out.println("Five golden rings,"); 
      case 4: System.out.println("Four calling birds,"); 
      case 3: System.out.println("Three French hens,"); 
      case 2: System.out.println("Two turtle doves, and a "); 
      case 1: System.out.println("Partridge in a pear tree!");
    }
  }
}
Next