| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Can I use variables in case clauses in the switch statement?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Can I use variables in case clauses in the switch statement?Yes and no. You must use compile time constant variables otherwise the code won't compile. The general form of the switch statement is:
switch (expression) {
case constant1:
statements // do these if expression == constant1
break;
case constant2:
statements // do these if expression == constant2
break;
case constant2:
case constant3:
case constant4: // Cases can simply fall thru.
statements // do these if expression == any of constant(2,3,4)
break;
. . .
default:
statements // do these if expression != any above
}
The
Each of the values specified in the case statements must be of a type compatible with or
assignable to the Here is example uses constant variable as the value of case clause.
....
final int a = 5;
final int b = 10;
//final int c; //c is final variable but not constant.
//c = 10;
switch (x) {
case a:
...
case b:
....
default:
}
Further ReadingMust all final variables be compile time constants?The switch statement in XyzWs |