MY mENU


Thursday 9 February 2012

Switch Statement

The Switch Statement allows for any number of possible execution paths.

An If-then-Else 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 enumerated value.

- A Switch works with the byte, short, char, and int primitive data types. It also works with enumerated types and a few special classes that "wrap" certain primitive types: Character, Byte, Short, and Integer.

Example :

class SwitchDemo {
public static void main(String[] args) {

int day = 3;
switch (day ) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid day .");break;
}
}
}

In this case, "Wednesday" is printed to standard output.

- The body of a Switch Statement is known as a Switch Block. Any statement immediately contained by the Switch Block may be labelled with one or more case or default labels. TheSwitch Statement evaluates its expression and executes the appropriate case.

- The break statement after each case terminates the enclosing Switch Statement. Control flow continues with the first statement following the Switch Block. The break statementsare necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements.

- The default section handles all values that aren't explicitly handled by one of the case sections.

Note: 

int day = 8;
switch (day ) {
    default: System.out.println("Invalid day .");
case 1: System.out.println("Monday");
case 2: System.out.println("Tuesday");
case 3: System.out.println("Wednesday");
case 4: System.out.println("Thursday");
case 5: System.out.println("Friday");
case 6: System.out.println("Saturday");
case 7: System.out.println("Sunday");

}
}

see the above example to there switch condition false and it terminates default case and there is no Break statement and it defined default at the top of the cases so it executes all the cases as output.

Output:

Invalid day .
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

No comments:

Post a Comment