File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting int to byte (was: pls explain) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic

Casting int to byte (was: pls explain)

vikram choudhary .

Joined: Apr 25, 2007
Posts: 7
byte i= (byte)129;

output: -127 why?
can anyone explain?
[ April 25, 2007: Message edited by: Barry Gaunt ]
anil kumar
Ranch Hand

Joined: Feb 23, 2007
Posts: 447

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
anil kumar
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710

so her the range exceeds by 3

3 or 2?


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.


Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
To avoid confusion please continue in this topic.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: Casting int to byte (was: pls explain)
It's not a secret anymore!