Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

switch statement case label in round up exam

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
this question appears in java round up exam,
----------------
question
----------------
In switch statement, the argument to the case label can be any variable which can fit into an int.
Answer given is
false,

Why is it so ,
i mean isn't all byte,short ,int or char (ie. which fit into an int) allowed in case label ?
then why is it false,
thanks in advance,
 
Steve Lovelace
Ranch Hand
Posts: 125
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It can't be just ANY such variable - it must also be final. The argument to case must be an expression such that the compiler can determine a constant value from it.
 
Chandra Sekhar
Ranch Hand
Posts: 90
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The answer is false because a long variable which is well with in the range
of int variable(means it will fit into a int variable) is also not allowed
in a switch.
Plzz correct me if I'm wrong
Thanks
Chandrasekhar S.
 
Alton Hernandez
Ranch Hand
Posts: 443
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given the following switch statement construct

the important rules to remember are:
1. <Expression> and <constant> must be of integral type i.e. byte, char, short, or int.
2. <constant> must be assignable to the <Expression> i.e. the value of <constant> must fit the <Expression>.
For example, no compilation error will occurr here even though l is an int and i is short.

but this would fail

[ October 01, 2003: Message edited by: Alton Hernandez ]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This can be stated as: - the type of the variable that appears in the switch statement (ie byte, char, short or int) must be such that all of the case values can be reached.
In the above example, with a byte variable type, if you have a case value outside the byte range (for example)

the compiler will object because the byte variable can never contain a value of 200 thus the case is unreachable. Thats the most-missed question in my "hardest" collection.
Bill
[ October 01, 2003: Message edited by: William Brogden ]
 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot everyone for the help
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic