Java

Java switch case statement

switch-case’ statement can be used as the alternative of ‘if-else-if’ statement where different conditions are defined in different ‘if’ statements. If the first condition returns false, then check the second condition and so on. Defining multiple conditions using this way is a very lengthy process. The same task can be done very simply by using a switch-case statement. It contains different execution parts and executes the statement where the particular value matches with any ‘case’ value. The switch statement can be applied to the various types of primitive data such as int, char, byte, etc. The different uses of switch-case statements in Java are explained in this tutorial.

Syntax:

switch(variable or expression) {
case value-1 :
Statement 1...N
break;
 
case value-2:
Statement 1...N
break;
 
.
.
.
 
case value-n:
Statement 1...N
break;
 
 
default :
Statement 1...N
}

Here, you can use any variable or expression in the switch part that will be matched with the case value. ‘break‘ statement and ‘default’ part are optional for the switch-case statement. But if the ‘break’ statement is omitted for any or all case statements, then the next case value or all case values will be checked with the defined value of the switch part. If none of the case value matches with switch value, then the statements of the default part will be executed. How the switch-case statement works with and without optional parts are shown below by using different examples.

Example-1: Use of switch-case statement without break and default

The following example shows how the switch-case statement works when no break and default statements are used. A string data will be taken as input and stored in the variable, ID, and the value of the ID will be checked with each case value. It will not only print the message where the case value match with the ID value but also print all the messages of the remaining case section because no break statement is used. If no case value matches with ID value, then no message will print because no default section is used in the code.

//Import Scanner package
import java.util.Scanner;

public class switch1 {

    public static void main(String[] args) {
       
        // Create a Scanner object
        Scanner input = new Scanner(System.in);
       
          System.out.print("Enter your ID: ");
          // Take string data from the user
        String ID = input.next();
       
        //Switch expression  
        switch(ID){  
       
            //Case statement-1
            case "0111786":
            System.out.println("Your batch is 24");  

            //Case statement-2
            case "0111234":
            System.out.println("Your batch is 20");  

            //Case statement-3
            case "0111923":
            System.out.println("Your batch is 37");  
       
       
        }  
        //Close the scanner object
          input.close();

    }

}

Output:

The following output will appear if the input value matches the first case value after executing the script. The last two messages are printed here for omitting the break statement.

When the input value matches the second case value, then the following output will appear.

When the input value does not match with any case value, then no output will appear for the omitting default section.

Example-2: Use of switch-case statement with default section

The default section is essential for a switch-case block to print a message for the user that no match is found. The following example shows the use of the default section in the switch-case block. Here, the value of the number will be checked with each case value of the switch-case statement, and no match is found, then the message of the default section will be printed.

public class switch2 {

    public static void main(String[] args) {   
       
        int number = 380;
        switch(number){  
               
            //Case statement-1
            case 440:
                System.out.println("You are selected for group A");  
           
            //Case statement-2
              case 500:
                System.out.println("You are selected for group B");  
           
              //Case statement-3
            case 890:
                System.out.println("You are selected for group C");  
           
            //Execute default statement if all case returns false
            default:
                System.out.println("Sorry, you are not selected");
        }  
               
    }

}

Output:

The following output will appear after executing the code. According to the code, the value assigned in the number variable does not match any case value. So, the message of the default section is printed here.

Example-3: Use of switch-case statement with default and break

The following example shows the use of a switch-case statement with the default section and breaks statement. Here, the course code will be taken as input from the user, and that will be checked with each case value. If any match exists, then the statements of the matching case section will be executed, and the program will terminate from the switch-case block for using a break statement. If no match exists, then the statements of the default section will be executed.

//Import Scanner package
import java.util.Scanner;

public class switch3 {

    public static void main(String[] args) {
        // Create an Scanner object
        Scanner input = new Scanner(System.in);
               
        System.out.print("Enter the course code: ");
        // Take string data from the user
        String code = input.next();
       
        switch(code){  
       
            //Case statement-1
            case "CSE-105":
                System.out.println("Course Name: Java Programming");
                System.out.println("Credit hour: 2");
                System.out.println("Semester: 2");
                break;
               
            //Case statement-2
            case "CSE-207":
                System.out.println("Course Name: Data Structure");
                System.out.println("Credit hour: 2");
                System.out.println("Semester: 4");  
                break;
           
            //Case statement-3
            case "CSE-402":
                System.out.println("Course Name: Artificial Intelligence");
                System.out.println("Credit hour: 3");
                System.out.println("Semester: 10");  
                break;
           
            //Execute default statement if all case returns false
            default:
                System.out.println("Invalid course code");
        }  
       
        //Close the scanner object
        input.close();

    }

}

Output:

After executing the code, it will ask for the course code from the user. Here, CSE-105 is taken as input that matches with the first case value. So, the details of the course information are printed, and other case sections are omitted for using a break statement.

Next, CSE-402 is taken as input that matches the last case value, and the corresponding course details are printed.

Next, CSE-101 is taken as input that does not match with any case value, and the message of the default section is printed.

Conclusion:

Using a switch-case statement is efficient in many cases instead of using the if-else-if statement for solving particular problems. The concept and the use of the switch-case statement are appropriately explained in this tutorial to help Java users to apply it efficiently in their code based on the requirement.

About the author

Fahmida Yesmin

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.