I came across below java line and puzzled about its output. Can you please explain me logic behind this code
System.out.println((int)(char)(byte) -1);
Output:
65535
I came across below java line and puzzled about its output. Can you please explain me logic behind this code
System.out.println((int)(char)(byte) -1);
Output:
65535
Well, it's equivalent to:
byte b = -1;
char c = (char) b; // c = '\uFFFF' - overflow from -1
int i = c; // i = 65535
Really the explicit conversion to int in the original is only to make it call System.out.println(int) instead of System.out.println(char).
I believe the byte to char conversion is actually going through an implicit widening conversion first - so it's like this really:
byte b = -1;
int tmp = b; // tmp = -1
char c = (char) tmp; // c = '\uFFFF'
Does that help at all?
char is unsigned in Java? Which makes it the only unsigned primitve.0xFFFF is not recognized by the console.char being the only unsigned primitive in Java.In java byte is a signed (twos-complement) 8-bit primitive type. The binary representation of a byte with a value of -1 is 11111111. This then gets cast to a char which is a 16-bit primitive with a value between \u0000 and \uFFFF (0 and 65535) - it would appear that the bits of the byte are left-shifted by 8, with sign-extension. So at this point the binary representation is:
1111111111111111
...or 65535. However, it is then not quite as simple as saying "Oh yes then it is turned into an int so we don't see the character representation and is printed out". In java, all numeric primitives are signed! If we cast the char as a short which is another 16-bit primitive, the program would output -1. However, when we cast it to a 32-bit int. The final binary representation becomes:
00000000000000001111111111111111
...which is 65535 both signed and unsigned!
In java, all numeric primitives are signed - No. The whole point of this exercise is to show that chars are unsigned in Java. Otherwise the result would be 0xffffffff and NOT 0xffff..In java, all numeric primitives are signed, by that I mean all primitives except chars, which do not represent numbers (kind of, maybe that was a bad choice of words..). I don't understand the second part of your repsonse, the result isn't 0xffff?