File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Type Cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Type Cast" Watch "Type Cast" New topic
Author

Type Cast

kantu Deshpande
Greenhorn

Joined: Sep 29, 2000
Posts: 13
Hi!!,
byte b;
int i=257;
b= (byte)i;
If I type cast as shown above, I'm getting answer b=1. But, if I intialize int i=144 I'm getting the answer b=-112. Can any body explain how this type casting been done. Please if you give me one example, I would really appreciate.
Thanks,
Kantu

Alagu Seenivasan
Greenhorn

Joined: Sep 30, 2000
Posts: 18
Originally posted by kantu Deshpande:
Hi!!,
byte b;
int i=257;
[b]b= (byte)i;

If I type cast as shown above, I'm getting answer b=1. But, if I intialize int i=144 I'm getting the answer b=-112. Can any body explain how this type casting been done. Please if you give me one example, I would really appreciate.
Thanks,
Kantu
[/B]

int i=257 is represented as 0000 0001 0000 0001
when you cast an int into byte only the lower order bits are copied
so byte b= 0000 00001 which is 1.

int i=144 is represented as 0000 0000 1001 0000
1001 0000 (in 2's complement form) represents -112.
-------------------
(to get the 2's complement of 112)
112 = 0111 0000
1' complement = 1000 1111
add 1 = 1001 0000

[ for more info search this forum for the words - 2's complement ]

[This message has been edited by Alagu Seenivasan (edited October 05, 2000).]
Jane Griscti
Ranch Hand

Joined: Aug 30, 2000
Posts: 3141
Hi ...
Another way to find the 2's complement is to subtract the number from the highest allowable value and set it negative

Hope that helps.
------------------
Jane


Jane Griscti
SCJP, Co-author Mike Meyers' Java 2 Certification Passport
bill bozeman
Ranch Hand

Joined: Jun 30, 2000
Posts: 1070
One thing that helped me with this is to remember that the minimum and maximum value for a byte is -128 and 127 (2 to the 7th and 2 to the 7th - 1). Both of the numbers you provided are out of this range, and that is when you start to get the funny answers. That is why Java makes you explicitly cast when you are casting down, because you might get a different answer than you expected because you are losing bits of information.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Type Cast
 
Similar Threads
RR #13
Byte b = new Byte(123); //fails to compile ! :mad:
Widening and narrowing conversion questions
How can it be valid?
byte + byte = int?