The Conditional Operator and the 'switch' Statement

6. Rules for switch Statements


Answer:

0.2

Rules for switch Statements

Here is what a switch statement looks like:

switch ( expression )
{
  case label1:
    statementList1 
    break;

  case label2:
    statementList2 
    break;

  case label3:
    statementList3 
    break;

  . . . other cases like the above

  default:
     defaultStatementList 
}

Here is how it works:

  • Only one case is selected per execution of the switch statement.
  • The value of expression determines which case is selected.
  • expression must evaluate to byte, short, char, or int primitive data, a String, or a few other types not discussed further here.
  • The type of expression and the type of the labels must agree.
  • Each label must be an integer literal (like 0, 23, or 'A'), a String literal (like "green"), but not an expression or variable.
  • There can be any number of statements in a statementList.
  • The statementList is usually followed with break;
  • Each time the switch statement is executed, the following happens:
    1. The expression is evaluated.
    2. The labels after each case are inspected one by one, starting with the first.
    3. The first label that matches has its statementList execute.
    4. The statements execute until a break statement is encountered.
    5. Now the entire switch statement is complete (no further statements are executed.)
  • If no case label matches the value of expression, then the default case is picked, and its statements execute.
  • If no case label matches the value of expression, and there is no default case, no statements execute.

Question 6:

Could the type of the expression be a float or a double?