This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes casting from int to byte Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting from int to byte" Watch "casting from int to byte" New topic
Author

casting from int to byte

Mathew Lee
Ranch Hand

Joined: Jun 08, 2009
Posts: 238
I was reading following lines from link
http://www.jchq.net/certkey/0501certkey.htm

did not understand it clearly.

>>>if you really want enough rope, Java uses the C/C++ convention of enclosing the data type with parenthesis i.e. (), thus the following code will compile and run

public class Mc{
public static void main(String argv[]){
byte b=0;
int i = 5000;
b = (byte) i;
System.out.println(b);
}
}
The output is

-120

I did bnot understand why output is -120 when i has 5000 value.
Any ideas, resources,sample code,links, highly appreciated. thanks in advance.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
Write down the binary string value of 5000, as in your other thread, strike out all but the rightmost 8 bits, and work out what that means in two's complement, with values of -128 (+)64 32 16 8 4 2 and 1 for the different bits going from left to right.
 
 
subject: casting from int to byte
 
Similar Threads
final local int narrowing and autoboxing
Byte Addition and Byte Range
casting
Primitive Assignments and Casting
Casting