Saturday, 4 January 2014

Switch Statement in Java

How to use Java Switch: Case: Default: 

Using switch statement

Swich:

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.It is an alternatives of else-if ladder. Switch allows you to choose a block of statements to run from a selection of code, based on the return value of an expression. The expression used in the switch statement must return an int, a String, or an enumerated value.


Let’s look at syntax of if statement:

switch (expression) {
case value_1 :
     statement(s);
     break;
case value_2 :
     statement(s);
     break;
 .
 .
 .
case value_n :
     statement(s);
     break;
default:
     statement(s);
}

Example for simple switch  statement

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

        int mon = 8;
        String monthStr;
        switch (mon) {
            case 1:  monthStr = "January";
                     break;
            case 2:  monthStr = "February";
                     break;
            case 3:  monthStr = "March";
                     break;
            case 4:  monthStr = "April";
                     break;
            case 5:  monthStr = "May";
                     break;
            case 6:  monthStr = "June";
                     break;
            case 7:  monthStr = "July";
                     break;
            case 8:  monthStr = "August";
                     break;
            case 9:  monthStr = "September";
                     break;
            case 10: monthStr = "October";
                     break;
            case 11: monthStr = "November";
                     break;
            case 12: monthStr = "December";
                     break;
            default: monthStr = "Invalid month";
                     break;
        }
        System.out.println(monthStr);
    }
}

Control Flow of switch Statement


Switch Statement line of control


1 comment :