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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Case Value " Watch "Case Value " New topic

Case Value

Sridhar Padala

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: 15082

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 8 API documentation
    Sridhar Padala

    Joined: Aug 03, 2007
    Posts: 20
    Thanks Young :-)
    I agree. Here's the link:
    subject: Case Value
    It's not a secret anymore!