• 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

byte to char conversion (was "doubt")

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
final byte b=1;
char c=2;
c=b;//line 1

works fine but

when final is removed as shown below:

byte b=1;
char c=2;
c=b;//line 1

line 1 gives compile error.


EDIT by mw: Changed subject to be descriptive.
[ March 02, 2007: Message edited by: marc weber ]
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by archana prabhu:
final byte b=1;
char c=2;
c=b;//line 1



In this code, b is a compile-time constant so its value is known at compile-time, so the compiler knows it will fit in a char.


byte b=1;
char c=2;
c=b;//line 1

line 1 gives compile error.



Here, b is not a compile-time constant, and there are values of bytes that cannot be assigned to a char.
 
shreya prabhu
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks a lot
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Keith Lynn:
...there are values of bytes that cannot be assigned to a char.


There's a little more to this. Even if the byte value is negative, those 8 bits can easily "fit" into 16. So how could there ever be a loss of precision?

It turns out that in converting from byte to char, the byte value is first widened to type int, and then the int is narrowed to type char. (See JLS 5.1.4.) It's in the narrowing that a loss of precision is possible, and this is why an explicit cast might be required.

Consider a byte value of -1, which is 11111111 in binary. With an explicit cast, you might expect the char value to be 00000000 11111111, with nothing "lost." But in fact...

Widening the byte to type int results in...
11111111 11111111 11111111 11111111

Then narrowing to type char (losing the first 16 bits of information in the int)...
11111111 11111111
 
reply
    Bookmark Topic Watch Topic
  • New Topic