Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 12 Apr 2016
break can be used to come out of the switch statement.

Break Switch Statement
class BreakSwitch
{
    public static void main(String arg[])
    {
        int rating = 1; // rating out of 4
        
        switch(rating)
        {
            case 1:
                System.out.println("Poor"); // LINE A
                break;
            case 2:
            case 3:
                System.out.println("Average"); // LINE B
                break;
            case 4:
                System.out.println("Good"); // LINE C
                break;
        }
        System.out.println("After switch"); // LINE D
    
    }
}
OUTPUT

Poor
After switch

DESCRIPTION

Here rating is 1 hence LINE A and LINE D are executed. When break is encountered after LINE A, the control directly goes to the next statement after switch, which is LINE D, hence prints After switch.
When rating is 2 or 3, LINE B and LINE D are executed, when it is 4, LINE C and LINE D will be executed.

THINGS TO TRY
  • Remove break statements at LINE A, LINE B, LINE C and see the output. The output will be as shown.
    Poor
    Average
    Good
    After switch

    Since there is no break all the cases will get executed.
  • Change the data type of rating to float. It shows a compilation error, since switch cannot function with float, double and long data types.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App