my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes switch question in Roundup Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch question in Roundup" Watch "switch question in Roundup" New topic
Author

switch question in Roundup

Douglas Wolfinger
Ranch Hand

Joined: Aug 28, 2000
Posts: 57
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

Joined: Jan 07, 2002
Posts: 2205
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
}


Rob
SCJP 1.4
 
wood burning stoves
 
subject: switch question in Roundup