Jim, This is a question from Bill Brogden's book. long lx=0x0FFFFL; short sx = (short)lx: There is a loss of information in this case since the higher order bit in sx is set and because short is a signed integer, this represents -1. I know you have mentioned in a previous mail also, short being -1 is not valid. Can you please explain me why the above is invalid? Thanks,
Well, it is valid in the sense that it will compile - it's legal code. The problem is, as you've noted, is that the conversion tranforms a long value of 65535 into a short value of -1. This is the sort of thing that can happen for any narrowing conversion involving primitives, especially integral types - the higher-order bits are lost, and the significance of the number can change completely. The compiler knows that narrowing conversions are dangerous, so it won't do them unless you tell it to by supplying the cast yourself. I'm not sure what previous quote of mine you're referring to. There's nothing inherently invalid about a short being equal to -1, unless you thought it was supposed to be something else, like 65535. (Which would be a clue that short is the wrong type to use here.) I hope that answered your question - if not, please clarify. What past post of mine are you referring to?
OK, you indicated elsewhere that it was this thread you were referring to. I don't see the conflict in my statements. A narrowing conversion is dangerous because it might cause the JVM to change the meaning of a number, but it's not illegal. Whether it's "valid" depends on whether you think "valid" means "legal" or "safe" I guess. If you want to be safe, you need to carefully consider what actual value you are dealing with when you convert it to another type. Is there valuable info in the higher-order bits? If you have no idea, here's one approach:
Jim, Thanks for the detailed explaination. I understand it clearly now - just make sure that the number you are converting fits into the one which you are converting into. I mean, i got it. Thanks again,