aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt from K&B ch 5 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt from K&B ch 5" Watch "Doubt from K&B ch 5" New topic
Author

Doubt from K&B ch 5

dhwani mathur
Ranch Hand

Joined: May 08, 2007
Posts: 621
I have a doubt from self test question 13
of chapter 5 as below......


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:
� 3 F is correct. A switch statement requires its case expressions to be constants,


i thought that the answer is B but it if F based on the above
reason but as both x2 and x4 are declared as final variables
than they are constants then why here error occurs on line 11

Please if anyone can explain me... where i am actualy going wrong
i dont know.....


Preparing SCJP 1.5
sankar kandasamy
Greenhorn

Joined: Sep 13, 2007
Posts: 13
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. }


Here x4 is declared as an Integer object not an
primitive int. So it is not a constant expression.
So it gives error
dhwani mathur
Ranch Hand

Joined: May 08, 2007
Posts: 621
Hi sankar!!!



What i think is although x4 is declared as Integer Object
it is final so its value wont change,hence constant....
now i am getting confused with above

Please can you ellaborate and explain the above
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424

What i think is although x4 is declared as Integer Object
it is final so its value wont change,hence constant....

Wrapper objects even static finals are not considered constants, hence invalid case constant.
dhwani mathur
Ranch Hand

Joined: May 08, 2007
Posts: 621
Thanks sankar and Ahmed

now i am clear with my doubt!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt from K&B ch 5
 
Similar Threads
Switch case Compiler error
Switch Statement
flow controls
mock question about "case"
Static