Jarrod to answer your questions then to show you how the answer you got is correct: Yes you can have short and byte literals. Any integral primitive can be expressed as a literal. A shorts range is from -32768 to 32767. In your piece of code what happened is that the initial value of a is set as 32767. In the next line you add 2 to that value (keep in mind that operations done on integral types promote the types to at least an int) so the result of a + 2 is an int with a value of 32769. If you look at this in binary form it looks like this: 00000000 00000000 10000000 00000001 When you cast it to a short it gets truncated and only the least significant (2 bytes on the right) are returned. So you get: 10000000 00000001 Which when converted back to a decimal is -32767. Hope that helps, if not post again and well clear it up for yuo.
Joined: Dec 24, 2002
Hi Dave, I quite didn't understand the last bit of your explanation:
10000000 00000001 Which when converted back to a decimal is -32767.
When I convert this binary -> 10000000 00000001 I get this in decimal -> (2^15) + (2^0) = 32769 How did you get -32767? Another scenerio: In the above example if a = 32766, then c = -32768 So, if I were to work through this with your above steps, I would get a+2 = 32768. In binary it would be: 00000000 00000000 10000000 00000000 After casting it to short I get: 10000000 00000000 Then if I were to convert this to decimal (according to you) I should get -32768, right? But I get 32768. Since short has a range of up to 32767, shouldn't I get a 'loss of precision' error instead on both of the examples? Thanks for your help and Merry Christmas!! -Jarrod
The highest order bit is the "sign bit" - if it is set, you get a negative number.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
In java, short is represented by 16 bit 2's complement, so 10000000 00000001 -> -(2^15) + (2^0) = -32767
Joined: Dec 24, 2002
Thanks guys. Could you please confirm my understanding of the material?: The highest order bit of the primitive data type represents the 'sign bit'. If it is 0, the number is always positive. If it is 1, the number is always negative. And if those are true, Dave's explanation indeed makes perfect sense!! -Jarrod
Joined: May 10, 2001
Jarrod That is indeed true. Glad it makes sense to you now.