Using Switch Statement in Java

The Switch statement in Java provides a means for executing one of several code blocks based on the value of an expression or variable. You set up the construct using the switch keyword followed by an expression or variable in parentheses. Inside the curly braces that follow, multiple case labels represent different potential values of the expression or variable. When a match is found, the code after that case label is executed. There's also the optional default label, which serves as a fallback. If none of the case labels match the expression or variable's value, the code under the default label will execute. In the Java Switch Statement example, a variable is evaluated within a switch construct to determine which block of code runs. Click Execute to run the Java Switch Statement Example online and see the result.
Using Switch Statement in Java Execute
public class SwitchDemo {
    public static void main(String[] args) {
        int color = 3;
        String colorName;

        switch (color) {
            case 1:
                colorName = "Red";
            case 2:
                colorName = "Green";
            case 3:
                colorName = "Blue";
                colorName = "Invalid color";

        System.out.println("The color is: " + colorName);
Updated: Viewed: 35 times