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

Not so primitive primitives

 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why this is OK:



But this is compiler error:

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A character has size 2 Bytes. A byte has size 1 Byte.

The compilier does not let you copy a character to a byte because of the possible loss of information.

You can force the compiler to do it for you by using the following cast, but then you as the programmer are responsible for eventuelly loss of information:



I think it is not considered as good style to use character to store numbers, personally I would prefer something like int.
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think the qusetion here is why is the below code that assigns a character literal to byte not flashing a compiler error
byte c = 'k';
Where as
char c1 = 'k'
byte c = c1;
shows a compiler error.
Thanks
Deepak
 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Deepak Jain:
I think the qusetion here is why is the below code that assigns a character literal to byte not flashing a compiler error
byte c = 'k';
Where as
char c1 = 'k'
byte c = c1;
shows a compiler error.
Thanks
Deepak




That is because the compiler knows that the value of 'k' will fit into a byte without any lost of precision. In the second case, it doesn't know that the char value held in "c1" will fit into a byte -- as c1 is not a compile time constant.

Henry
 
Andry Dub
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you!
I didn't know this nuance.
 
reply
    Bookmark Topic Watch Topic
  • New Topic