#17 Java Control Statements part 4

switch Statement (case of)

The switch provides for a multi-way branch. Thus, it enables a program to select among several alternatives. Although a series of nested if statements can perform multi-way tests, for many situations the switch is a more efficient approach.

switch(expression) { 
case constant1: 
statement sequence 
break; 
case constant2: 
statement sequence 
break; 
case constant3: 
statement sequence 
break; ... 
default: 
statement sequence

}

 The switch expression can be of type char, byte, short, or int. (Floating-point expressions, for example, are not allowed.)
 Frequently, the expression controlling the switch is simply a variable.
 The case constants must be literals of a type compatible with the expression.
 No two case constants in the same switch can have identical values.
 The default statement sequence is executed if no case constant matches the expression. The default is optional; if it is not present, no action takes place if all matches fail. When a match is found, the statements associated with that case are executed until the break is encountered or, in the case of default or the last case, until the end of the switch is reached.

The following program demonstrates the switch.


 // Demonstrate the switch.
class SwitchDemo { 
public static void main(String args[]) { 
int i; 
for(i=0; i<10; i++) 
switch(i) { 

case 0: 
System.out.println("i is zero"); 
break; 

case 1: 
System.out.println("i is one"); 
break; 

case 2: 
System.out.println("i is two");
break; 

case 3: 
System.out.println("i is three"); 
break; 

case 4: 
System.out.println("i is four"); 
break; 
default: 
System.out.println("i is five or more"); 
       }
     }
}

The output produced by this program is shown here:
i is zero 
i is one i is two 
i is three 
i is four 
i is five or more 
i is five or more 
i is five or more 
i is five or more 
i is five or more

The break statement is optional, although most applications of the switch will use it. When encountered within the statement sequence of a case, the break statement causes program flow to exit from the entire switch statement and resume at the next statement outside the switch. However, if a break statement does not end the statement sequence associated with a case, then all the statements at and following the matching case will be executed until a break (or the end of the switch) is encountered. For example,

Comments

Popular Posts