wood burning stoves*
The moose likes Java in General and the fly likes Case Value 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 » Java » Java in General
Bookmark "Case Value " Watch "Case Value " New topic
Author

Case Value

Sridhar Padala
Greenhorn

Joined: Aug 03, 2007
Posts: 20
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

Joined: May 08, 2007
Posts: 621
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

Joined: Aug 16, 2005
Posts: 14074
    
  16

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.


    Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
    Scala Notes - My blog about Scala
    Sridhar Padala
    Greenhorn

    Joined: Aug 03, 2007
    Posts: 20
    Thanks Young :-)
     
    It is sorta covered in the JavaRanch Style Guide.
     
    subject: Case Value
     
    Similar Threads
    confused with switch statement
    Case expression assignment
    switch case
    switch statement
    about switch case in core java