What is Java Switch Statement ? How it Works ?

What is Java Switch Statement ? How it Works ?


If you’ve not been paying attention to the Java language closely, then you might have overlooked some changes that have occurred to a basic language keyword. The switch statement has gotten a bit of attention and has been given some new capabilities.

Consider a piece of code using the switch statement:

    String month = "October";
    int days = 0;
    switch (month) {
        case "February":
            days = 28;
            break;
        case "April":
        case "June":
        case "September":
        case "November":
            days = 30;
            break;
        case "January":
        case "March":
        case "May":
        case "July":
        case "August":
        case "October":
        case "December":
            days = 31;
            break;
        default:
            days = 0;
            break;
    }

As you can see, this code simply takes a textual month and determines the number of days. If the value assigned to month is “October,” then days will be set to 31.  Of course, this code is the same as:

    String month = "October";