This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch() construct

 
cyril vidal
Ranch Hand
Posts: 247
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jon Dornback
Ranch Hand
Posts: 137
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Bred Tom
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the last one is compiled?
The MAX_VALUE of short is 32767.
 
venu gopal
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi cyril,
Good catch.
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13048
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 443
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
May I also add that this is possible:
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic