This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Case expression assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Case expression assignment" Watch "Case expression assignment" New topic
Author

Case expression assignment

ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

Hi ,

The expression in a switch statement should be a compile time constant ie it can take int , byte , char, short ie any type which can be cast into an int . If instead of int i take a byte argument as in the following code :-

byte g=1;
switch(g){

case 23:

case 128:
}

This results in compile time error as the case argument 128 is too large for a byte . My question is g has already been implicitly converted to an int . Now so it is an integer which is being compared in the case statement . Then why are we getting the error .
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

My question is g has already been implicitly converted to an int

No it will not be implicitly converted to an int. The case constants must be assignable to the switch expression. Since the switch expression is of type byte, the value 128 is out of its range so you get an error...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
ragi singh
Ranch Hand

Joined: Mar 10, 2010
Posts: 198

Thank you Ankit , i got it
 
 
subject: Case expression assignment