This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
What is the result of attempting to compile and run the above program? a. Prints: v w x y b. Prints: v w x y z Default c. Prints: v y w z d. Prints: Default Default Default Default e. Runtime Exception f. Compiler Error g. None of the Above ANSWER: C EXPLANATION: The constant case expressions can be any expression that is assignable to the type of the switch expression. 'd'-'a'=3. ~0=-1. 4&5=4. ----------- I thought that the rules for what is allowed as x for " case x: " are as follows: (1) x must be assignable to the variable in the switch statement (2) x can be byte, char, short, or int only (3) According to Mughal, "case labels are constant expressions" *this is where I am unsure* When I think "constant expressions", I think of values that are known at compile time. Such as the number 7 or a final int variable j. But, 'd'-'a', ~0, 4&5 are computed at runtime, right? any insight will be very much appreciated. [ Jess added [URL=http://www.javaranch.com]UBB [CODE] tags ] [ August 19, 2002: Message edited by: Jessica Sant ]
I think that compile time computable expressions are also candidate for x in case x I think only limitation is that x should result in an integral value. Anyone: correct me if I am wrong? Thanks Barkat [ August 19, 2002: Message edited by: Barkat Mardhani ]
Hi Jesica: I think it is difference in term of reference. Bruce Eckel (Thinking in Java) is saying that "expression should result in an integral value". The types in your quote will all result in integral values including char. If there is any other type that results in integral value, then we have a confict... Thanks Barkat
My mock exam has two questions that are very similar.
Result: Prints: v y w z Remark: The constant case expressions can be any expression that is assignable to the type of the switch expression. 'd'-'a'=3. ~0=-1. 4&5=4.
Result: Compiler Error Remark: The switch expression can not be of type long. The legal types for the switch expression are byte, short, char, and int. The question and answer that started this thread don't agree because the second question was paired with the first answer.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>