• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Case expression assignment

 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
ragi singh
Ranch Hand
Posts: 198
Oracle Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ankit , i got it
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic