10x Blogs Directory

Monday, March 9, 2009

Switch Statements

  • switch
    -allows branching on multiple outcomes.
  • switch statement has the form:
switch( switch_expression )
{
case case_selector1: statement1;
// statement2;
//block 1 break;
case case_selector2: statement1;
// statement2;
//block 2 break;
default: statement1;
// statement2;
//block n
}
  • where,
    -switch_expression
    lis an integer or character expression
    -case_selector1, case_selector2 and so on,
    lare unique integer or character constants.
  • When a switch is encountered,
    -Java first evaluates the switch_expression, and jumps to the case whose selector matches the value of the expression.
    -The program executes the statements in order from that point on until a break statement is encountered, skipping then to the first statement after the end of the switch structure.
    -If none of the cases are satisfied, the default block is executed. Take note however, that the default part is optional.
  • NOTE:
    -Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly braces.
    -When a case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed.
    -To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.

Coding Guidelines

  • Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use, based on readability and other factors.
  • An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique.

No comments:

Post a Comment