jQuery in Action, 2nd edition*
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 Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply locked New topic
Author

Casting int to byte (was: pls explain)

vikram choudhary .
Greenhorn

Joined: Apr 25, 2007
Posts: 7
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

Joined: Feb 23, 2007
Posts: 447
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

Joined: Feb 28, 2007
Posts: 1707

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


cmbhatt
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: http://aspose.com/file-tools
 
subject: Casting int to byte (was: pls explain)