Monday, October 28, 2013

Flow Controls - switch

The switch statements is java's multiway branch statement. It provides an easy way to c execution to different parts of your code based on the value of an expression. As such, it offers a better alternative the a large series of if else if statements the General form of a witch statement;
switch (expression) {
 
 case value 1 :   // Statement sequence
                         break;
 case value 2 :  // Statement sequence
                        break;
 case value 3 :  // Statement sequence
                        break;
default           : // default statement sequence

}

The expression must be of type byte, short, int or char each of the value specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is , it must be a constant, not a variable) duplicate case values are not allowed.

The switch statement works like this:

 the value of the expression is compared with each of the literal values in the case statements. if a match is found, the code sequence following that case statement is executed.
class Switch {

    public static void main(String[] args) {
        int switchValue = 3;

        switch (switchValue) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("three");
                break;
            case 4:
                System.out.println("Four");
                break;
            default:
                System.out.println("Not Match");
        }
    }
}
Output
three

if none of the constants matches the values of the expression. then the default statement is executed. However, 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. when a break statement is encountered,execution branches to the first line of code that follows the entire switch statement, This has the effect of jumping out of the switch.
class Switch {

    public static void main(String[] args) {
        int switchValue = 3;

        switch (switchValue) {
            case 1:
                System.out.println("One");
            case 2:
                System.out.println("Two");
            case 3:
                System.out.println("three");
            case 4:
                System.out.println("Four");
            default:
                System.out.println("Not Match");
        }
    }
}
Output
three
Four

Not Match

No comments:

Post a Comment