• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting

 
Ajit Deshpande
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Casting{
public static void main(String argv[]){
byte b=0;
int i = 4999;
b = (byte) i;
System.out.println(b);
}
}
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.
Thanks
 
Ankur Gupta
Ranch Hand
Posts: 66
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Ankur
[This message has been edited by Ankur (edited July 06, 2000).]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic