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
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?