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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "switch() construct" Watch "switch() construct" New topic
Author

switch() construct

cyril vidal
Ranch Hand

Joined: Jul 02, 2003
Posts: 247
What I knew up to now about switch/case construct:
1�) the variable x in switch(x) must be either byte, short, char or int. It must not be long, either of the floating-point types, boolean, or an object reference.
2�) The arguments to case labels must be compile constant expression according to JLS 15.28:

# Simple names that refer to final variables whose initializers are constant expressions
# Qualified names of the form TypeName . Identifier that refer to final variables whose initializers are constant expressions

3�) What I've just learned from Bill Brogden's Questions is that the type used in the switch statement must accommodate all of the values in the case statements
Thus, this will not compile:

because of lines 2 and 3 in which range > 127.
But this wil compile with success:

Maybe it's worth knowing this...
Cyril.


SCJP 1.4, SCWCD, SCBCD, IBM XML, IBM Websphere 285, IBM Websphere 287
Jon Dornback
Ranch Hand

Joined: Apr 24, 2002
Posts: 137
that is definitely worth knowing - I never would have noticed that otherwise. everytime i think i'm ready for the exam, i find out something like that and it ruins my confidence!


use the [CODE] tags - it makes it much easier for people to help you.
Bred Tom
Greenhorn

Joined: Jul 07, 2003
Posts: 11
Why the last one is compiled?
The MAX_VALUE of short is 32767.
venu gopal
Ranch Hand

Joined: Nov 21, 2000
Posts: 40
Hi cyril,
Good catch.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12759
    
    5
That question is the most frequently missed one in my "Hardest" collection.
I think the most important thing it points out is - don't jump to conclusions as to what a question is about.
I suspect people read the question and jump to the conclusion that it is about the requirement for a variable that can be promoted to int in the switch statement. Then they look at the options and choose everything but long and charge on to the next question.
Bill
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
May I also add that this is possible:
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: switch() construct
 
Similar Threads
tipsmart Q25
switch type
question on integer promotion / assignment
what are compile time constant
Super and sub class