Meaningless Drivel is fun!*
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 Murach's Java Servlets and JSP this week in the Servlets 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: 9291
    
  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
 
jQuery in Action, 2nd edition
 
subject: Case expression assignment
 
Similar Threads
Mike Meyers' Certification Passport Java2 by Cindy Glass et.al (Osborne/McGraw-Hill)
switch comparison vs == comparison
switch statement
about switch case in core java
Case Value