Java Switch Case Example



Java Switch Case Example demonstrates how to use a switch-case statement with an example in Java.

The Java switch statement executes one statement from multiple conditions. It is like an if-else-if ladder statement. The switch statement works with a byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

Syntax

Here is the general form of a switch statement:
switch (expression) {
    case value1:
        // statement sequence
        break;
    case value2:
        // statement sequence
        break;
        .
        .
        .
        case valueN:
            // statement sequence
            break;
    default:
        // default statement sequence
}

Java switch case Simple Example

The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of the month, using the switch statement.
public class SwitchDemo {
    public static void main(String[] args) {

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

Comments