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 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting" Watch "Casting" New topic


Ajit Deshpande

Joined: Jun 15, 2000
Posts: 17
public class Casting{
public static void main(String argv[]){
byte b=0;
int i = 4999;
b = (byte) i;
If this code is compiled and run the value of b is 3 which I expected.
However when I use 'int i = 5000;' the value of b comes to -120 which is unexpected.
Can anybody please explain this strange output.
Ankur Gupta
Ranch Hand

Joined: Jun 13, 2000
Posts: 66
Binary equivalent of 4999 = 1001110000111
Binary equivalent of 5000 = 1001110001000
When u convert 4999 to byte it just takes 8 LSB(least significant bits). The answer should be -121 and not 3.
Decimal eq of byte(5000)= 10001000 = -120 as u had mentioned.
Hope it is clear now.
[This message has been edited by Ankur (edited July 06, 2000).]
I agree. Here's the link:
subject: Casting
It's not a secret anymore!