This week's book giveaway is in the Performance forum.We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!

# Casting a byte to an int....

Bob Graffagnino
Ranch Hand
Posts: 81
The following code is from a JQ+ question.
<pre><font size="+0.3">
public static void main(String args[ ] )
{
byte b = -128 ;
int i = b ;
b = (byte) i;
System.out.println(i+" "+b);
}
</font></pre>
What is the output of the program? I guessed 128 -128.
The answer is -128 -128! I figured the JVM would preserve the 2^8 bit and add a bunch of zero's to the start on the int. What's going on here?
Thanks!
Bob

Rob Ross
Bartender
Posts: 2205
Originally posted by Bob Graffagnino:
The following code is from a JQ+ question.
public static void main(String args[ ] )
{
byte b = -128 ;
int i = b ;
b = (byte) i;
System.out.println(i+" "+b);
}
What is the output of the program? I guessed 128 -128.
The answer is -128 -128! I figured the JVM would preserve the 2^8 bit and add a bunch of zero's to the start on the int. What's going on here?
Thanks!
Bob

byte b = -128 : since this will "fit" into a byte variable, this is no problem. b has value -128, in hex: 0x80
int i = b; //byte b is widened to int. It does the "right thing" regarding the widening, *always*. i has value -128, or OxFFFFFF80 hex.
b = (byte) i; //i is cast to a byte via a narrowing conversion. The low-order byte is copied to b, so b gets -128 , Ox80 hex.
Then it prints both i and b, both of which have the value -128.
Hope this clears it up!
Rob

[ January 16, 2002: Message edited by: Rob Ross ]