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

Willie Toma
Ranch Hand
Posts: 78
byte b=(byte)256;
System.out.println("B = " + b);
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
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

Bill Krieger
Ranch Hand
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

 It is sorta covered in the JavaRanch Style Guide.