Vijay Kumari
Describe the Switch Statement.
By Vijay Kumari in Java on Sep 17 2019
  • Rohit Gupta
    Sep, 2019 17

    Syntax

    1. Switch(variable)
    2. {
    3. case 0:
    4. .
    5. .
    6. .
    7. case n-1:
    8. default:
    9. }

    This is a type of control statement in which we are a single variable is checked for multiple values and if neither value matches the code corresponding to default is executed.

    • Switch case does not allow variables to be taken as the case value.
    • Only uniques case values are acceptable.
    • Each case is suffixed by a break statement, to make sure that only the matched case code executes
    1. import static java.lang.System.out;
    2. class Csharpcorner
    3. {
    4. public static void main(String[] args)
    5. {
    6. int i=0;
    7. switch(i)
    8. {
    9. case 0:
    10. case 1:
    11. case 2:
    12. case 3:
    13. case 4:
    14. case 5:
    15. case 6:out.print(i);
    16. break;
    17. default: out.print("No value");
    18. }
    19. }
    20. }

    For a detailed tutorial on Java Control and Loop Statements please visit https://www.c-sharpcorner.com/article/java-loops-and-control-statements/

    • 1
  • Lohiths S
    Aug, 2021 12

    switch statement is used to choose one of the blocks of code to get some output. Here in switch statement switch expression is evaluated once and compared with each “case” value.

    Syntax:

    `
    switch(expression)
    {
    case 1 value :
    // code goes here
    break;

    case 2 value :
    // code goes here
    break;

    case 3 value :
    // code goes here
    break;
    .
    .
    .
    .

    default: // optional
    // default code goes here
    }
    `
    Advantages of switch statement

    1. Easy to read than if-else statement
    2. More efficient than if-else statement 3. Easy to debug.
    3. Easy to maintain.
    4. Execution potential of switch statement is fast.

    • 0
  • Laxmidhar Sahoo
    Dec, 2019 15

    1. switch (variable/expression) {
    2. case value1:
    3. // statements
    4. break;
    5. case value2:
    6. // statements
    7. break;
    8. .. .. ...
    9. .. .. ...
    10. default:
    11. // statements
    12. }

    Here the variable should be premitive datatype like byte,int short,char .floating point is not allowed .For more follow the link
    https://www.programiz.com/java-programming/switch-statement

    another link
    https://www.javatpoint.com/java-switch

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS