Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting

 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why compiler error?
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suspect that the compiler converts the hex constant 0xFF to the decimal int constant 255 at an early stage . You can't write
byte b = 255;
because the range of byte is from -128 to 127.
Similarly, the compiler is probably converting
0xFFFFFFFF to -1, which is a legal value of byte,
so no complaint from the compiler on that one.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The actual error (1.4) is "possible loss of precision found: int required:byte"
To me that suggests that the compiler has widened
the 0xFF to 0xFFFFFFFF and then realises it is
going to leave most of that behind when it sticks it back into b1.
Why that's not considered to be the same as byte b2 = 0xFFFFFFFF; is beyond me; another java gotcha I guess.
As Ron said, byte b = 255; gives the same error from the compiler.
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"0xFF" is an int constant literal. It doesn't widen to 0xFFFFFFFF, it is already 0x000000FF.
Java doesn't have byte or short constant literals, just int constants.
If an int constant has a value that is within the range of a short or byte or char, then you can assign without casting.
[ September 10, 2002: Message edited by: Ron Newman ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ahha! So the 0x000000FF is the thing it's stuffing into a byte. So it complains now because the result is going to be negative, and not positive as the 0x000000FF is.
The "loss of precision" error message is confusing then, because I associate it with the chopping off of the 24 high-order bits which 0x000000FF doesn't have.
No, it does have the bits, but they're all 0. So it's a loss of information really.
Have I understood it now?
Learned a thing today.
-Barry
[ September 10, 2002: Message edited by: Barry Gaunt ]
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Loss of precision" is a very misleading error message.
If you assign a double to an int, you can lose precision (decimal places) due to rounding.
If you assign an int to a byte, you can lose the magnitude and possibly even the sign, which is very different from losing precision.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic