Java Switch Statement with Multiple Case Values

Learn how to use a Java switch statement with multiple case values to execute the same block of code for a range of numbers.

Code Explanation (Step-by-Step)

  • Creates a Scanner object to read input from the keyboard.
  • Uses sc.nextInt() to read an integer value entered by the user.
  • Passes the entered number to the switch statement.
  • Cases 1, 2, 3, 4, and 5 are grouped together to execute the same code block.
  • If the entered number is between 1 and 5, it prints “Number range is 1 to 5”.
  • The break statement terminates the switch block.
  • If no case matches, the default block executes and prints “number is out of range”.
  • Closes the Scanner object using sc.close().
				
					import java.util.Scanner;

public class SwitchRangeTest {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the input number:");
        int num = sc.nextInt();

        switch (num) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                System.out.println("Number range is 1 to 5");
                break;

            default:
                System.out.println("Number is out of range");
        }

        sc.close();
    }
}
				
			

Output :
Enter the input number:
2
Number range is 1 to 5

Enter the input number:
8
Number is out of range

Java Program to Group Multiple Cases in Switch

				
					import java.util.Scanner;

public class GradeCategory {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println("Enter grade:");
        char grade = sc.next().charAt(0);

        switch (grade) {

            case 'A':
            case 'B':
                System.out.println("Excellent Performance");
                break;

            case 'C':
            case 'D':
                System.out.println("Good Performance");
                break;

            case 'E':
                System.out.println("Needs Improvement");
                break;

            default:
                System.out.println("Invalid Grade");
        }

        sc.close();
    }
}
				
			

FAQ
Can a switch statement have multiple case values in Java?
Yes. Multiple case labels can share the same code block by placing them consecutively without a break statement.
Does Java support range values directly in a switch statement?
No. Java does not support ranges such as 1-5 directly in switch cases. Multiple case labels must be specified individually.
What is the purpose of the break statement?
The break statement stops execution and exits the switch block after a matching case is executed.
What happens when no case matches?
The default block executes if no case value matches the input.
Can switch statements work with strings?
Yes. Java supports String values in switch statements starting from Java 7.