Java switch-case Statement

The switch-case statement is a type of selection statement in Java that allows a program to evaluate a single variable or expression and execute a different block of code depending on its value. It is often used as an alternative to if-else statements when there are multiple conditions to be evaluated. The basic syntax of a switch-case statement is as follows:

switch (variable/expression) {
  case value1:
    // code to be executed if variable/expression is equal to value1
    break;
  case value2:
    // code to be executed if variable/expression is equal to value2
    break;
  ...
  default:
    // code to be executed if variable/expression does not match any of the cases
}

Here’s how the switch-case statement works:

  1. The program first evaluates the variable or expression inside the parentheses of the switch statement.
  2. It then compares the value of the variable or expression to the values in the case statements.
  3. If there is a match, the code inside that case statement is executed until a break statement is encountered.
  4. If there is no match, the code inside the default block is executed (if it is present).

Here’s an example program that uses the switch-case statement:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter a month number (1-12): ");
    int month = scanner.nextInt();

    String monthName;
    switch (month) {
      case 1:
        monthName = "January";
        break;
      case 2:
        monthName = "February";
        break;
      case 3:
        monthName = "March";
        break;
      case 4:
        monthName = "April";
        break;
      case 5:
        monthName = "May";
        break;
      case 6:
        monthName = "June";
        break;
      case 7:
        monthName = "July";
        break;
      case 8:
        monthName = "August";
        break;
      case 9:
        monthName = "September";
        break;
      case 10:
        monthName = "October";
        break;
      case 11:
        monthName = "November";
        break;
      case 12:
        monthName = "December";
        break;
      default:
        monthName = "Invalid month";
    }
    System.out.println("The month is " + monthName);
  }
}

In this program, the user is prompted to enter a month number between 1 and 12 using the Scanner class. The program then uses a switch-case statement to evaluate the value of the month variable and assign the corresponding month name to the monthName variable. Finally, it prints the month name to the console.

You can try running this code with different inputs to see how the switch-case statement works.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author