Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting a byte to an int....

 
Bob Graffagnino
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic