The switch statement in Java is used to make decisions based on a specific value. It’s helpful when you have several options to choose from, so instead of using many if-else statements, you can use switch to make the code easier to read.

Here’s the basic structure of a switch statement:

switch (expression) {

    case value1:

        // Code to run if expression equals value1

        break;

    case value2:

        // Code to run if expression equals value2

        break;

    // Add more cases as needed

    default:

        // Code to run if none of the cases match

}

Explanation:

  1. expression: This is the variable you want to check.
  2. case value: Each case checks if the expression matches a specific value. If it does, the code in that case runs.
  3. break: This ends the case so the program doesn’t run into the next one.
  4. default: This is optional; it runs if no cases match.

Example

Let's say you want to print the day of the week based on a number:

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;

    default:

        System.out.println("Invalid day");

}

In this example, since day is 3, the output will be "Wednesday".

Comments

Post a Comment

Popular posts from this blog