Switch case in java

 

In Java programming, a switch statement (also called a switch-case) is a control flow statement that allows you to execute one block of code out of many based on the value of an expression.

It is an alternative to using many if-else statements, and is often more readable and efficient when dealing with multiple conditions based on a single variable.


🔹 Syntax of switch-case in Java:

switch (expression) {
    case value1:
        // Code block for value1
        break;
    case value2:
        // Code block for value2
        break;
    // more cases...
    default:
        // Default code block (optional)
}

🔸 How it works:

  • The expression is evaluated once.
  • Its value is compared with each case.
  • If a match is found, the corresponding code block runs.
  • The break statement exits the switch block. Without break, execution "falls through" to the next case.
  • The default block runs if none of the cases match. It is optional.

Example:

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");
}

Output:

Wednesday

🔹 Supported Data Types in switch:

Java switch supports:

  • Primitive types: byte, short, char, int
  • String (since Java 7)
  • enum types
  • Wrapper classes (Byte, Short, Character, Integer)

🔸 Notes:

  • From Java 14 onwards, you can also use the enhanced switch expression, which allows returning values from cases and eliminates the need for break.


Comments

Popular posts from this blog

S ram

Data transport

Data ware house