in this article, we will learn to switch case statement in Java in an easy way. The switch statement is used to select one of the many code blocks to be executed.


Syntax:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}


  • if the condition is not matched, the default block will be executed
  • break keyword, it breaks out of the switch block


Example:

package javaapplication;

import java.util.Scanner;

/**
 *
 * @author Rathorji
 */
public class JavaApplication {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int number = 58;
        String size;

        // switch statement to check size
        switch (number) {

            case 30:
                size = "Small";
                break;

            case 40:
                size = "Medium";
                break;

            // match the value of week
            case 50:
                size = "Large";
                break;

            case 58:
                size = "Extra Large";
                break;

            default:
                size = "Unknown";
                break;

        }
        System.out.println("Size: " + size);

    }

}


output:

run:
Size: Extra Large