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: ....;
}
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: ....;
}
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
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:
case
defined after default
case it is matched first instead of the default
onedefault
case understandably makes all tested values fall through from itself downObserve especially the test for 23
- the result would be different if case 23
and default
was swapped (both will be matched then).
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
}
© 2022 - 2024 — McMap. All rights reserved.
default
case as it's aSwitchLabel
like any other. The only restriction is that you cannot have more than 1default
case in the same switch statement. – Erdmann