• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Assignment

 
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

class T3{
public static void main(String a[]){
byte b = 1;
char c = 2;

c=b; //error can not assign byte to character.}}

***********************************************************************

class T3{
public static void main(String a[]){
final byte b = 1;
char c = 2;

c=b; // No Error
}}

My Question is

When Final value of byte is getting assigned to character its not giving error[Second code] but when simple "byte" is getting assigned to "char" its giving compile time Error[Firrst Code].
What is the reason behind this?

Thanks
[ March 04, 2008: Message edited by: sandhi mridul ]
 
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
The difference between byte and char types is first byte is 8-bit long whereas char is 16-bit long and second byte is stored as a signed number which means it can be positive or negative. Chars are unsigned. The conclusion is that the compiler does not accept assignment of byte to char unless it is 100% sure this value will fit to char representation without loss of data. If it is about explicitely given value the byte variable stores and it will never change like in case of final modifier, say 5, it's OK for char to hold it and that's what the compiler does. However if you try to take a variable of byte type and attempt to assign it to a char variable without specifying it's final the compiler will complain because the value may still change and then might not fit into character range. If you know you really want to assign byte to char without compiler error you can explicitely cast it to char.
[ March 04, 2008: Message edited by: Paul Prusko ]
 
sandhi mridul
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Paul.

Your explanation left no point for any further confusion.
[ March 04, 2008: Message edited by: sandhi mridul ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic