Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use 'continue' inside a switch statement in Java?

Why is it that the following code:

class swi  
{
    public static void main(String[] args)  
    {  
        int a=98;
        switch(a)
        {
            default:{ System.out.println("default");continue;}
            case 'b':{ System.out.println(a); continue;}
            case 'a':{ System.out.println(a);}
        }
        System.out.println("Switch Completed");
    }
}

Gives the error:

continue outside of loop

like image 374
abson Avatar asked Mar 26 '10 07:03

abson


People also ask

Why cant we use continue in switch?

Switch is not considered as loop so you cannot use Continue inside a case statement in switch...

Can we use continue inside switch case?

The continue statement is not used with the switch statement, but it can be used within the while loop, do-while loop, or for-loop.

What is not allowed in a switch statement?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

What are the limitations of switch statement in a Java?

Disadvantages of switch statementsfloat constant cannot be used in the switch as well as in the case. You can not use the variable expression in case. You cannot use the same constant in two different cases. We cannot use the relational expression in case.


1 Answers

Falling through is the standard behavior for a switch statement and so, consequently, using continue in a switch statement does not make sense. The continue statement is only used in for/while/do..while loops.

Based on my understanding of your intentions, you probably want to write:

System.out.println("default");
if ( (a == 'a') || (a == 'b') ){
    System.out.println(a);
}

I would also suggest that you place the default condition at the very end.

EDIT: It is not entirely true that continue statements cannot be used inside switch statements. A (ideally labeled) continue statement is entirely valid. For example:

public class Main {
public static void main(String[] args) {
    loop:
    for (int i=0; i<10; i++) {
        switch (i) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 9:
            continue loop;
        }

        System.out.println(i);
    }
}
}

This will produce the following output: 0 2 4 6 8

like image 187
Michael Aaron Safyan Avatar answered Nov 04 '22 04:11

Michael Aaron Safyan