Hi all, Could somebody address the pitfalls of the switch statement aside from the known basics that default should be the last label in the construct?
In this code, default is the first label, and, since no case is a match, the output will start from the default println() statement (of course, the break must be commented out to compile, is it normal for non-standard labels only?). Also, the syntax of labels... Well, it's known that user-defined label can be used with labeled loops only.
Hi, Vad - I'll give you the perspective of a C programmer making the switch (no pun intended) to Java: For efficiency, place your case statements in order from most-often matched to least-often matched, if possible. This way, the JVM doesn't have to waste processor cycles testing cases that rarely match. (That's assuming the JVM works similarly to an O/S under compiled C code.) Otherwise, I know of no pitfalls to using a switch, other than to make sure you use a break statement if you don't want processing to fall through the following statements. No matter what your last case statement is, use a break after it to avoid the potential problem of a programmer coming in after you and adding another case, which could cause your case to drop through to the new statement if the other programmer didn't think to put a break between the last statement and the new one. Cheers, Jeff [ September 02, 2003: Message edited by: Jeff Bosch ]
Vad, is this what you want to know: JLS 14.10 The switch Statement You can practice with Dan Chisholm's exam on Flow Control Single Topic: Section 2 Control [ September 04, 2003: Message edited by: Marlene Miller ]
Thanks for the link Marlene. My question is if it's legal to use labels other then case or default in the switch construct (see the code above) and what happens if they are used in combination with break statement in terms of reachability (please refer to the same code above).
My question is if it's legal to use labels other then case or default in the switch construct
According to JLS 14.10, a switch label has one of these forms: case ConstantExpression: default: Is ConstantExpression meaningful to you?
what happens if they are used in combination with break statement in terms of reachability
According to JLS 14.20, a statement in a switch block is reachable if: o It bears a case or default label, or o There is a statement preceding it in the switch block and that preceding statement can complete normally. case 1: throw new Exception(); ; //this statement is unreachable
default should be the last label in the construct
It�s okay for the default label to be anywhere in the switch block. [ September 04, 2003: Message edited by: Marlene Miller ]