Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Can I use variables in case clauses in the switch statement?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ: Can I use variables in case clauses in the switch statement?

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 switch expression must be of type byte, short, int, char, or enumerated type (in Java 5). Other numeric types of long, float, and double can not be used in switch expression except you explicit cast them to int.

Each of the values specified in the case statements must be of a type compatible with or assignable to the switch expression. Each case value must be a compile time constant/expression, not a variable. No two of the case constant expressions associated with a switch statement may have the same value.

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 Reading

Must all final variables be compile time constants?
The switch statement in XyzWs

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help