Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Case Value

 
Sridhar Padala
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

The below Code is giving compile time error because 128 is not in byte range. But I read that switch will type cast it to int by default. So in this case byte will cast to int and 128 is in the range of int.If I am wrong,please advice on this


public class SwitchDemo
{
public static void main(String args[])
{
byte g = 2;
switch(g) {
case 23:
case 128:
}}
}

Thanks in Advance
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi sridhar

you said the below shown code gives you compile time error
than how is it possible that switch can cast an byte to int
if it must have casted than i think you must have not got the
compile time error .......isnt it?
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15276
38
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Section 14.11 of the Java Language Specification says:

All of the following must be true, or a compile-time error will result:
  • Every case constant expression associated with a switch statement must be assignable (�5.2) to the type of the switch Expression.
  • ...


  • Since 128 is not assignable to the type byte, you will get a compile-time error.
     
    Sridhar Padala
    Greenhorn
    Posts: 20
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks Young :-)
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic