Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# 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 ]