Switch

What is Switch Statements

The switch statement evaluates an expression. Match the value of the expression with a range of case clauses. Executes statements that match the first case clause until a break statement is encountered.

In simple terms, the Java switch statement executes an instruction based on several conditions. This statement is similar to an if-else-if ladder statement. It provides a simple way to send execution to different parts of code depending on the value of the expression. The expression is essentially a byte, short, char, or int primitive data type. The main objective of this test is to determine if variables are equal to multiple values.

A few things to remember:

  1. One or N cases values can be used for a switch expression.
  2. Switch expression type is the only type of case value that can be used. The case value is required to be either literal or constant. Variables are not allowed by it.
  3. The case values must be unique. If duplicated, it makes the build-time error.
  4. The expression of the Java switch should be byte, short, int, long (with its Wrapper type), enums and chain.
  5. The case value may have a default labeling that is optional.

How Java Switch Statements works :

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of each case.
  • If there is a match, the associated block of code is executed.
  • The break and  default keywords are optional, and will be described later in this chapter

The switch statement is a control flow construct used to make decisions based on the value of an expression. It provides an alternative way to write multiple if-else statements when you have several possible cases to handle.

Syntax for switch statement:

switch (expression) {

case value1:

// Code to execute when the expression is equal to value1

break;

case value2:

// Code to execute when the expression is equal to value2

break;

//More cases can be added as needed

default:

// Code to execute when none of the cases match the expression

}

Explanation:

  1. switch (expression): Evaluate a value or expression.
  2. case value1:  If the value matches value1, proceed.
  3. break; : Stop the switch after value1 case.
  4. case value2: If the value matches value2, proceed.
  5. break; : Stop the switch after value2 case.
  6. // More cases can be added as needed: Add more cases if needed.
  7. default:  If no match, proceed with default code.

Flowchart of switch Statement

Here’s an example of a simple switch statement that converts numeric values:

public class Switch {

    public static void main(String[] args) {

        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");
                    break;
        }
         
    }

}

Output:

Three

Explanation:

  1. public class Switch { : Starts a Java class named “Switch”.
  2. public static void main(String[] args) { : Begins the main part of the program.
  3. int number = 3; : Sets the value of a number variable to 3.
  4. switch (number) { : Checks the value of the number variable.
  5. case 1: – If the number is 1:
    • System.out.println(“one”); – Print “one” to the screen.
    • break; – Stop checking cases.
  6. case 2: – If the number is 2:
    • System.out.println(“Two”); – Print “Two” to the screen.
    • break; – Stop checking cases.
  7. case 3: – If the number is 3:
    • System.out.println(“Three”); – Print “Three” to the screen.
    • break; – Stop checking cases.
  8. default: – If none of the cases match:
    • System.out.println(“Other”); – Print “Other” to the screen.
    • break; – Stop the switch.
  9. } : Ends the switch.
  10. } : Ends the main method.
  11. } : Ends the class.

The break keyword in Switch:

The break keyword is used within the switch statement to terminate the execution of the switch block. When Java encounters a break statement, it immediately exits the switch block, and the program continues to execute the code after the switch statement. It prevents fall-through behavior, which means without a break, the program will continue executing subsequent case blocks after the matching one, even if their conditions are not true.

Here’s an example to illustrate the usage of break:

public class Switch {

    public static void main(String[] args) {

        int dayOfWeek = 3;
        switch (dayOfWeek) {
        case 1: 
            System.out.println("Monday"); 
        break;
        case 2:
            System.out.println("Tuesday"); 
            break; 
            case 3:
                System.out.println("Wednesday");
                break; 
                default: 
                    System.out.println("other day");
                    break;
        }
         
    }

}

Output:

Wednesday

Explanation:

  1. public class Switch { : Starts a class named “Switch“.
  2. public static void main(String[] args) { : The main part of the program begins.
  3. int dayOfWeek = 3; : Sets the day of the week as “Wednesday” (3).
  4. switch (dayOfWeek) { : Checks the day of the week.
  5. case 1: – If it’s 1 (Monday):
    • System.out.println(“Monday”); – Prints “Monday“.
    • break; – Stops checking cases.
  6. case 2: – If it’s 2 (Tuesday):
    • System.out.println(“Tuesday”); – Prints “Tuesday“.
    • break; – Stops checking cases.
  7. case 3: – If it’s 3 (Wednesday):
    • System.out.println(“Wednesday”); – Prints “Wednesday“.
    • break; – Stops checking cases.
  8. default: – If none match:
    • System.out.println(“other day”); – Prints “other day“.
    • break; – Stops the switch.
  9. } : Ends the switch.
  10. } : Ends the main method.
  11. } : Ends the class.

The default keyword in Switch:

The default keyword is used to specify a block of code that is executed when none of the case values match the value of the expression being evaluated. It provides a fallback option for situations where none of the defined cases apply. The default case is optional, and you can omit it if you don’t need to handle cases that don’t match the specified values.

Here’s an example:

public class Switch {

    public static void main(String[] args) {

        int dayOfWeek = 7;
        switch (dayOfWeek) {
        case 1: 
            System.out.println("Monday"); 
        break;
        case 2:
            System.out.println("Tuesday"); 
            break; 
            case 3:
                System.out.println("Wednesday");
                break; 
                default: 
                    System.out.println("Weekend day");
                    break;
        }
         
    }

}

Output:

Weekend day

Explanation:

  1. public class Switch { : Starts a class named “Switch“.
  2. public static void main(String[] args) { : The main part of the program begins.
  3. int dayOfWeek = 7; – Sets the day of the week to 7 (which might represent Sunday in this context).
  4. switch (dayOfWeek) { – Checks the value of the day of the week.
  5. case 1: – If the day is 1 (Monday):
    • System.out.println(“Monday”); – Prints “Monday“.
    • break; – Stops checking cases.
  6. case 2: – If the day is 2 (Tuesday):
    • System.out.println(“Tuesday”); – Prints “Tuesday“.
    • break; – Stops checking cases.
  7. case 3: – If the day is 3 (Wednesday):
    • System.out.println(“Wednesday”); – Prints “Wednesday“.
    • break; – Stops checking cases.
  8. default: – If none of the above cases match:
    • out.println(“Weekend day”); – Prints “Weekend day“.
    • break; – Stops the switch.
  9. } : Ends the switch.
  10. } : Ends the main method.
  11. } : Ends the class.

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close