Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must the "default" case come last in a switch?

In a switch statement in java, is it necessary that the "default" case be the last one? For example, can I do something like the following:

switch(x) {
case A: ....;
default: ....;
case B: ....;
}
like image 709
Kricket Avatar asked May 04 '15 07:05

Kricket


1 Answers

No.. But it is suggested to put it at the end to make the code more readable. The code shown below works fine.

public static void main(String[] args) {

    int i = 5;
    switch (i) {
    default:
        System.out.println("hi");
        break;

    case 0:
        System.out.println("0");
        break;
    case 5:
        System.out.println("5");
        break;
    }
}

O/P : 5
like image 122
TheLostMind Avatar answered Oct 21 '22 06:10

TheLostMind