Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

mock question about "case"

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chapter 5 Question 13. Given:
1. class Ring {
2. final static int x2 = 7;
3. final static Integer x4 = 8;
4. public static void main(String[] args) {
5. Integer x1 = 5;
6. String s = "a";
7. if(x1 < 9) s += "b";
8. switch(x1) {
9. case 5: s += "c";
10. case x2: s += "d";
11. case x4: s += "e";
12. }
13. System.out.println(s);
14. }
15. }
What is the result?
A. abc
B. abcde
C. Compilation fails due only to an error on line 7.
D. Compilation fails due only to an error on line 8.
E. Compilation fails due only to an error on line 10.
F. Compilation fails due only to an error on line 11.
G. Compilation fails due to errors on multiple lines.
============================
Answer:
F is correct. A switch statement requires its case expressions to be constants, and wrapper variables (even final static ones) aren�t considered constants. The rest of the code is correct.
A, B, C, D, E, and G are incorrect based on the above. (Objective 2.1)

========================
my question is...x2 is final static, how would it go through? (just because it is not a wrapper class?)
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15642
47
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by adam lui:
my question is...x2 is final static, how would it go through? (just because it is not a wrapper class?)

Yes, that's exactly the reason.

Some more info: The Java Language Specification, section 14.11 says that case expressions must be constant expressions, as explained in section 15.28. An instance of a wrapper class is not a constant expression. (In practice it is constant because the wrapper classes are immutable, but the Java compiler doesn't know that the wrapper classes are immutable).
[ September 05, 2007: Message edited by: Jesper Young ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic