my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static 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 "Static " Watch "Static " New topic
Author

Static

Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
Hi Folks

Following code is from K&B:-

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. }

"The answer is compilation fails due to line 11. Because 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."

My question is if line 11 is causing a Compilation error then line 10 should also cause for same error. But in answer they are only considering line 11 . It make me confuse.

megha joshi
Ranch Hand

Joined: Feb 20, 2007
Posts: 206
Hi,

At line 10 the case expression is a constant, its a final static int as opposed to line 11 which is a final static Integer.

So line 10 does not cause a compilation error.Its case expression is a constant .
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707



Gaurav says,
My question is if line 11 is causing a Compilation error then line 10 should also cause for same error. But in answer they are only considering line 11 . It make me confuse.


x2 is an int constant, x4 is a wrapper constant. Wrapper object can't be
treated as a constant in the case. Although wrapper objects are immutable(that can't be changed) but where primitive constant (enum as well ) is required, wrapper can't be used.



Regards,
cmbhatt


cmbhatt
Gaurav Pavan Kumar Jain
Ranch Hand

Joined: Mar 19, 2007
Posts: 168
Thank you very much Megha & Chandra



Anish Agrawal
Greenhorn

Joined: Apr 25, 2007
Posts: 3
Hi All,

final static Integer x4 = 8;

The compilation error is due to this statement.It doesnot compile and we
get the error "Type mismatch;cannot convert from int to Integer".

We can't assign an int value directly to an Integer type.
It can be done like this:

Integer x4=new Integer(8);

But it can't be used as a case constant.

Thanks and Regards,
Anish
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static
 
Similar Threads
Doubt from K&B ch 5
Switch case Compiler error
Switch Statement
flow controls
mock question about "case"