Kricket
Kricket

Reputation: 4179

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: ....;
}

Upvotes: 18

Views: 12164

Answers (4)

helvete
helvete

Reputation: 2673

It surely is not necessary, but beware it will behave a lot differently in case fall-through is used.

int[] test = {0,1,5,23,24};
for (int t: test) {
    System.out.println(String.format("Running test: %s", t));
    switch(t) {
    case 0:
        System.out.println(String.format("Match: %s", 0));
    default:
        System.out.println(String.format("Match: %s", "default"));
    case 23:
        System.out.println(String.format("Match: %s", 23));
    }
}

Prints:

Running test: 0
Match: 0
Match: default
Match: 23
Running test: 1
Match: default
Match: 23
Running test: 5
Match: default
Match: 23
Running test: 23
Match: 23
Running test: 24
Match: default
Match: 23

This simply speaking means:

  • if there is an exact (non-default) case defined after default case it is matched first instead of the default one
  • if there is not, then the default case understandably makes all tested values fall through from itself down

Observe especially the test for 23 - the result would be different if case 23 and default was swapped (both will be matched then).

Demo: https://ideone.com/LyvjXQ

Upvotes: 2

Java wanna bee
Java wanna bee

Reputation: 3107

The default statement can be placed anywhere inside switch statement body

   switch (i) {

          // the default statement can be placed anywhere inside the switch statement body

    }

Upvotes: -2

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 25

duffy356
duffy356

Reputation: 3718

no, the default statement could also be the first one.

Upvotes: 6

Related Questions