• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

AutoBoxing - Compilation Error

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,
Need your help to understand why following is failing to compile.

final byte b = 2;
Integer y = 3;
switch (y)
{
case b:
System.out.println("x is equal to 2");
break;
default:
System.out.println("no idea what x is");
}

Where as following compiles fine.

final int b = 2;
Byte y = 3;
switch (y)
{
case b:
System.out.println("x is equal to 2");
break;
default:
System.out.println("no idea what x is");
}
Thanks.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
According to the Java Language Specification

Every case constant expression associated with a switch statement must be assignable (�5.2) to the type of the switch Expression.

Note that you can't do this

,

but you can do this

.
 
Ali Javaid
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks a lot for the answer. But I am still confused why compiler has a problem with

final byte b = 3;
Integer y = b;

where as following compiles fine

final byte b = 3;
Integer y = new Integer(b);

I was thinking may be compiler is not supporting any implicit casting in case of AutoBoxing, but why following is possible then

final int b = 3;
Byte y = b;

Even though more often compiler is happier to do widening as compared to narrowing of primitives.
 
Ali Javaid
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I got the answer to why following compiles
final int b = 3;
Byte y = b;
Since b is compile time constant. If I remove final, it fails compilation too.
So it means, compiler is not supporting implicit casting in case of AutoBoxing. Is it correct?
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic