Java Switch Statement With Examples

The Java programming language offers various control structures to handle these situations efficiently. One such structure is the “switch statement”, a powerful tool for executing different blocks of code based on the value of an expression. In this blog post, we will explore the Java switch statement, its syntax, use cases, and provide some examples to better understand its functionality.

The Syntax of the Switch Statement

The switch statement is a multi-branch decision-making structure that allows us to evaluate a single expression against multiple constant values. Its syntax is as follows:

switch (expression) {
    case value1:
        // Code block executed if 'expression' matches 'value1'
        break;
    case value2:
        // Code block executed if 'expression' matches 'value2'
        break;
    // More cases can be added as needed
    default:
        // Code block executed if 'expression' doesn't match any 'case'
}

switch statement

The switch statement begins with the keyword “switch,” followed by the expression to evaluate in parentheses.

case lables

Inside the block, we have multiple “case” labels, each representing a constant value to be compared with the expression. If a case matches the value of the expression, the corresponding block of code will be executed.

break statement

The “break” statement is crucial, as it exits the switch block after the corresponding case is executed, preventing fall-through to other cases.

default case

If the expression doesn’t match any of the given “case” lables, then the default block is executed.

Expression in Switch Statement

The expression used in the switch statement can be of various types, including:

  • Primitive Types: The switch statement can be used with primitive data types, such as byte, short, int, char, and long. Since Java 7, it also supports the use of the wrapper classes for these primitive types, such as Byte, Short, Integer, Character, and Long.

  • Enum Types: Java switch statements are particularly useful with enum types. Enums provide a fixed set of constants, and the switch statement can easily handle different enum constant cases.

  • String Type: Since Java 7, the switch statement can also be used with strings. This means you can evaluate a string expression and compare it against various string constants.

  • Character Sequences (Java 12 and later): In Java 12, the switch statement was further enhanced to allow the use of character sequences (e.g., String, StringBuffer, StringBuilder) as expressions.

It’s important to note that the Java switch statement does not support floating-point types (float and double) as expressions. This is because floating-point numbers may have some precision issues, leading to unreliable comparisons.

Java Switch Statement Examples

Let’s demonstrate the use of the switch statement with different types of expressions:

Primitive Types, int

public class SwitchExpressionTypes {
    public static void main(String[] args) {
        // Example with int (primitive type)
        int number = 3;
        switch (number) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            case 3:
                System.out.println("Three");
                break;
            default:
                System.out.println("Other");
        }
    }
}

Primitive Types, char

import java.util.Scanner;

public class CharSwitchExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a character: ");
        char inputChar = scanner.next().charAt(0);

        switch (inputChar) {
            case 'A':
            case 'a':
                System.out.println("The input is a vowel 'A'");
                break;
            case 'E':
            case 'e':
                System.out.println("The input is a vowel 'E'");
                break;
            case 'I':
            case 'i':
                System.out.println("The input is a vowel 'I'");
                break;
            case 'O':
            case 'o':
                System.out.println("The input is a vowel 'O'");
                break;
            case 'U':
            case 'u':
                System.out.println("The input is a vowel 'U'");
                break;
            default:
                System.out.println("The input is a consonant");
        }
    }
}

Enum

public class SwitchExpressionTypes {
    public static void main(String[] args) {
       
        // Example with enum
        Fruit fruit = Fruit.APPLE;
        switch (fruit) {
            case APPLE:
                System.out.println("Apple");
                break;
            case ORANGE:
                System.out.println("Orange");
                break;
            case BANANA:
                System.out.println("Banana");
                break;
            default:
                System.out.println("Unknown Fruit");
        }

        enum Fruit {
            APPLE, ORANGE, BANANA
        }
    }
}

String

public class SwitchExpressionTypes {
    public static void main(String[] args) {
        
        // Example with string
        String day = "MONDAY";
        switch (day) {
            case "MONDAY":
                System.out.println("Start of the week");
                break;
            case "FRIDAY":
                System.out.println("End of the week");
                break;
            default:
                System.out.println("Weekday");
        }
    }
}

Use Cases of the Java Switch Statement

The switch statement is particularly useful when you have a series of discrete values to check against a single expression. Some common use cases include:

  1. Handling menu options: You can use a switch statement to execute different actions based on user-selected menu options in a console or graphical user interface (GUI) application.

  2. Processing enums: Switch statements work well with Java enums, allowing you to perform specific operations based on the type of enum constant.

  3. Implementing state machines: When building complex applications with different states, a switch statement can manage the transitions between states based on specific events.

  4. Handling error codes: The switch statement can be used to handle error codes returned from functions and take appropriate actions based on the error type.

Conclusion

The Java switch statement is a valuable control structure that simplifies decision-making and code execution based on discrete values. It allows developers to write cleaner and more efficient code when dealing with multiple possible outcomes. By incorporating the switch statement into your Java programs, you can make your code more readable and maintainable, enhancing overall productivity and clarity in your projects. Happy coding!