Switch case with multiple values for the same case

Execution continues until it reaches a break;. Therefore, you can list cases one after the other to get the following code execute on either one of those cases.

String commentMark(int mark) {
    switch (mark) {
        case 0 : // Enter this block if mark == 0
            return "mark is 0" ;
        case 1:
        case 2:
        case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
            return "mark is either 1, 2 or 3" ;
        // etc.
        default :
            return "mark is not 0, 1, 2 or 3" ;
    }
}

The return statements above serve to get out of the function. If you do not want to return, you have to use break; after each block, of course. This code below is equivalent to the one above.

String commentMark(int mark) {
    String msg;
    switch (mark) {
        case 0 : // Enter this block if mark == 0
            msg = "mark is 0" ;
            break;
        case 1:
        case 2:
        case 3: // Enter this block if mark == 1 or mark == 2 or mark == 3
            msg = "mark is either 1, 2 or 3" ;
            break;
        // etc.
        default:
            msg = "mark is not 0, 1, 2 or 3" ;
            break; // this is a good habit, in case you change default to something else later.
    }
    return msg;
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)