wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes casting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "casting" Watch "casting" New topic
Author

casting

Willie Toma
Ranch Hand

Joined: May 11, 2001
Posts: 78
byte b=(byte)256;
System.out.println("B = " + b);
Answer:
Since the integer's value (256) is larger than the byte's range (-128 - +127), the result is the remainder of the division of the integer value by the byte's range (256).
This is displayed:
B = 0
The Answer given states that it should be 127/256?
Does someone understand why this is so? If not, forget about it!
Dave Vick
Ranch Hand

Joined: May 10, 2001
Posts: 3244
Willie
When you do a narrowing conversion, which is what you're doing here, what happens is that all but the lowest bits are discarded. In your case 256 in binary is:
00000000 00000000 00000001 00000000
so after the conversion all that is left is the lowest order 8 bits, or 00000000. And that, of course, is 0.
hope that helped

------------------
Dave
Sun Certified Programmer for the Java� 2 Platform


Dave
Bill Krieger
Ranch Hand

Joined: Sep 27, 2001
Posts: 53
Originally posted by Willie Toma:
:
Since the integer's value (256) is larger than the byte's range (-128 - +127), the result is the remainder of the division of the integer value by the byte's range (256).
The Answer given states that it should be 127/256?

This statement is correct, if somewhat unclear. The byte's range is 256. The integer value is 256. The remainder of the division of the integer value (256) by the byte's range (256) is the remainder of 256/256 which is zero. In other words:
byteValue = (byte) intValue;
assigns (intValue % 256) to the byte. If this value is from 128 to 255, the byte value becomes a negative number from -128 to -1.
Bill
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: casting
 
Similar Threads
Downcasting to Byte
Why the result of (byte)(-128) is -128
whizlabs question
Implicit and explicit casts give different results?
byte pool