It's not a secret anymore!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting a byte to an int.... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting a byte to an int...." Watch "Casting a byte to an int...." New topic
Author

Casting a byte to an int....

Bob Graffagnino
Ranch Hand

Joined: May 30, 2001
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

Joined: Jan 07, 2002
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 ]

Rob
SCJP 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Casting a byte to an int....
 
Similar Threads
Math.abs()
Loop concerns
switch-case problem
isn't this strange?
help for shopping cart