Bookmark Topic Watch Topic
  • New Topic

Casting int to byte (was: pls explain)

 
vikram choudhary .
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Report post to moderator
byte i= (byte)129;
System.out.println(i);

output: -127 why?
can anyone explain?
[ April 25, 2007: Message edited by: Barry Gaunt ]
 
anil kumar
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
  • Report post to moderator
hi
vikram

byte range is -128 to 127

if you assign any value out of this range it will give compile time error
like this
byte b=130;

if you type cast to byte like this
byte b=(byte)130;
it will print -126

when it is out of range it again start from -128
so her the range exceeds by 3
-128,-127,-126
Thanks
anil kumar
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Report post to moderator

so her the range exceeds by 3


3 or 2?

Anyways,

A byte has 8 bit capacity, the most significant bit is for sign and all other
seven LSB (least significant bits) are for value.

If the limit exceeds, all the top bits of the the right hand side(int literal)
value is discarded.



Regards,
cmbhatt
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Report post to moderator
To avoid confusion please continue in this topic.
 
    Bookmark Topic Watch Topic
  • New Topic