Switch Statement in Java | Control Flow in Java

The switch statement in Java is a control flow statement that allows a variable to be tested for equality against multiple values. Each value is called a case, and the variable being switched on is checked for each case.

Key Points on Switch Statement:

Syntax of Switch Statement:

Syntax Example

switch (expression) {
            case value1:
                // Code to execute if expression equals value1
                break;
            case value2:
                // Code to execute if expression equals value2
                break;
            // More cases
            default:
                // Code to execute if none of the cases match
        }

Example of Switch Statement in Java:

This example uses a switch statement to determine the day of the week based on a number.

Code Example

public class Weekday {    
            public static void main(String[] args) {    
                int day = 3;    
                switch (day) {    
                    case 1:    
                        System.out.println("Monday");    
                        break;    
                    case 2:    
                        System.out.println("Tuesday");    
                        break;    
                    case 3:    
                        System.out.println("Wednesday");    
                        break;    
                    case 4:    
                        System.out.println("Thursday");    
                        break;    
                    case 5:    
                        System.out.println("Friday");    
                        break;    
                    case 6:    
                        System.out.println("Saturday");    
                        break;    
                    case 7:    
                        System.out.println("Sunday");    
                        break;    
                    default:    
                        System.out.println("Invalid day");    
                }    
            }    
        }

Output

Wednesday

Switch Statement Flowchart:

The flowchart below shows the control flow of a switch statement.

Flowchart of switch statement in Java

Detailed Explanation:

Using switch statements effectively helps make code cleaner and more readable when handling multiple conditions based on constant values.