Java Switch Statment

Java Switch Statement

The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements.

Syntex
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
case valueN:
// statement sequence
break;
default:
// default statement sequence
}

The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. The value of the expression is compared with each of the literal values in the case statements. the default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the switch to terminate a statement sequence.

Example
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6 0:="" 1:="" 2:="" 3.="" 3:="" break="" case="" default:="" greater="" i="" is="" one.="" pre="" switch="" system.out.println="" than="" three.="" two.="" zero.="">
The output produced by this program is shown here
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
As you can see, each time through the loop, the statements associated with the case constant that matches i are executed. All others are bypassed.

Example 2
class MissingBreak {
public static void main(String args[]) {
for(int i=0; i<12 0:="" 10="" 1:="" 2:="" 3:="" 4:="" 5:="" 5="" 6:="" 7:="" 8:="" 9:="" break="" case="" default:="" i="" is="" less="" more="" or="" pre="" switch="" system.out.println="" than="">
This program generates the following output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more
As you can see, execution falls through each case until a break statement (or the end of the switch) is reached.
Nested switch Statements
You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch.

Syntex
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...

0 Comments