Rules for switch Statements

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

0.2

Rules for switch Statements

Here is what a switch statement looks like:

switch ( integerExpression )
{
  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 integerExpression determines which case is selected.
  • integerExpression must evaluate to an integer type (including char).
  • Each label must be an integer literal (like 0, 23, or 'A'), 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 integerExpression 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 the break statement is encountered.
    5. Now the entire switch statement is complete.
  • If no case label matches the value of integerExpression, then the default case is picked, and its statements execute.

QUESTION 6:

Would you believe that there are even more rules for the break-statement?