KnowledgeBoat Logo

Computer Applications

What will happen if 'break' statement is not used in a switch case? Explain.

Java Conditional Stmts

16 Likes

Answer

Use of break statement in a switch case statement is optional. Omitting break statement will lead to fall through where program execution continues into the next case and onwards till end of switch statement is reached.

Consider the below example:

int shape = 2;
    
switch(number) {
    
    case 0:
        System.out.println("Circle");
        break;

    case 1:
        System.out.println("Triangle");
        
    case 2:
        System.out.println("Square");

    case 3:
        System.out.println("Rectangle");
        
    case 4:
        System.out.println("Pentagon");
        break;

    default:
        System.out.println("Shape not found in the list!");
        break;
        
}

Here, we have omitted break statement in cases 1, 2 and 3. When the program executes with the value of control variable as 2, 'Square' will be printed on the screen. Since no break statement is encountered, 'Rectangle' and ' Pentagon' will also be printed. Finally, in case 4 break statement will act as a case terminator and the control will come out of the switch case.

Answered By

8 Likes


Related Questions