Control Flow

Switch Case in Java

A switch case is used test variable equality for a list of values, where each value is a case. When the variable is equal to one of the cases, the statements following the case are executed.


Syntax
switch(variable) { 
    case valueOne: 
        //statements 
        break; 
    case valueTwo: 
        //statements
        break; 
    default: //optional
    //statements
}

Notes

A break statement ends the switch case. The optional default case is for when the variable does not equal any of the cases.

The variable used in a switch statement can only be a short, byte, int, char, or the String class (Java 7 and up). The values for each case must be the same data type as the variable type.


Example
char choice;
switch(choice) { 
    case 'Y' : 
        System.out.println("Yes"); 
        break; 
    case 'M' : 
        System.out.println("Maybe"); 
        break; 
    case 'N' : 
        System.out.println("No"); 
        break; 
    default: 
        System.out.println("Invalid response"); 
}

Add to Slack

< If Statement   |   Ternary Operator >

© 2018 SyntaxDB. All Rights Reserved.