public static void main(String args)
char ch = -90;
when i run the above code its gives a compilation error - possible loss of precision. My doubt is when i give char ch = 90; i get an out put z, despite of the fact that 90 is taken 32 bit integer which is put into a 16 bit char. How is ch =-90 a different from that.
JLS - 5.2 Assignment Conversion explains...
...if the expression is a constant expression (�15.28) of type byte, short, char or int ... [a] narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.
In this example, the value of the constant expression is negative, so it is not representable in the type of the variable (which must be positive).
[ November 06, 2007: Message edited by: marc weber ]
short 90 is 0000 0000 0101 1010
short -90 is 1111 1111 1010 0110
Now if we put 1111 1111 1010 0110 in a (unsigned type) char, shouldn't it be taken as decimal 65446 which would fall well within the range of char type(0 - 65536).
So char ch should accept a value -90 ??.
I am not very sure about my knowledge in bit calculations.
Originally posted by Deepa Priyesh:
...Now if we put 1111 1111 1010 0110 in a (unsigned type) char, shouldn't it be taken as decimal 65446 which would fall well within the range of char type(0 - 65536)...
That is exactly what would happen if you forced the assignment using an explicit cast...
But without the explicit cast (which tells the compiler that you understand you might be losing information), char x = -90; simply isn't allowed.
Going back to my quote from the Java Language Specification above, when it says, "the value of the constant expression," this means the decimal value (which is -90) -- not the binary representation (which could mean different things depending on the context).
[ November 10, 2007: Message edited by: marc weber ]