Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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

Win a copy of Badass: Making Users Awesome this week in the Game Development forum!
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: 1707

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)