Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch question in Roundup

 
Douglas Wolfinger
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I just finished a Roundup session. Question #223 asks:
True or False. In a switch statement, the argument to the case label can be a var which can fit within an int.
Answer: False. The case argument must be either an int literal, or an int-compatible var which is a constant (i.e., static final).
I'm confused. The byte in this program is not a constant, but can fit within an int, and it works.
class Switch2 {
byte x = 0;
Switch2() {
switch(x) { }
}
public static void main(String args[]) {
new Switch2();

}
}
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have a single case label in your switch statement.
You can't do this:
byte x = 5;
int y = 2;
static final z = 5;
switch(x){
case 1: // int literal
case z: //compile time constant
case y: //compiler error!!! can't use a var here
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic