Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
Willie Toma
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic