java
  1. java-switch

Java Switch Statement

Syntax

switch(expression) {
  case value1:
    // statements
    break;
  case value2:
    // statements
    break;
  ...
  default:
    // statements
}

Example

int day = 3;
String dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  case 6:
    dayName = "Saturday";
    break;
  case 7:
    dayName = "Sunday";
    break;
  default:
    dayName = "Invalid day";
}

System.out.println(dayName);

Output

Wednesday

Explanation

A switch statement is used to execute different statements based on different values. It evaluates an expression, matches the expression's value to a case label, and executes the statements associated with that case.

In the example above, we have a switch statement with the expression day. The code checks the value of day and executes the statements associated with that value. In this case, the value of day is 3, so dayName is set to "Wednesday".

If the value of the expression does not match any of the case labels, the statements associated with the default label are executed.

You may also have multiple statements associated with a case, which can be written simply by putting them inside curly braces.

Use

The switch statement is commonly used in Java when you need to execute different statements based on different values. It is frequently used to replace long if-else chains, as it is usually easier to read and understand. It can be used with any data type that can be compared through the equals() method, such as integers, characters, and strings.

Important points

  • The expression inside a switch statement must evaluate to a primitive data type, an enumeration, or a String.
  • The case labels must be unique and constant.
  • Only one set of statements associated with a case will be executed.
  • The default block is optional but helpful when no cases match the expression.
  • You can use the break keyword to exit the switch block and prevent fall-through.

Summary

The switch statement in Java allows you to execute different sets of statements based on a specified value. It is commonly used to replace long if-else chains, and can be used with any data type that can be compared through the equals() method. The switch statement must have a default case and the break statement is used to exit the switch statement.

Published on: