Diansonn
Diansonn

Reputation: 7

How can it prints '?' in Java when I try to print char(-1)

I'm reading Java Puzzlers these days, in question 6, it mentioned the transformation in basic data types. Then I want to have a try of convertting (-1) to char and print it. It should print the ascii code of -1, right? But there's no a character whose ascii is -1 and there's someone told me it should be 255 instead. And in fact it output '?', is there anyone can give me a reason?

Thank you, thank you all in Thanksgiving Day.

Upvotes: 1

Views: 106

Answers (2)

Michael Berry
Michael Berry

Reputation: 72379

Putting -1 in a char will overflow it to 0xFFFF (because it's an unsigned 16 bit value.) 0xFFFF is a non-character, hence the ?.

If the character produced by the overflow is not a non-character, it would show up fine:

char x = (char)-65500;
System.out.println(x); //Prints $

Same principle, only this time we've overflowed to a value that actually has a defined character attached to it (36, the dollar symbol.) Note there's no practical application of this - you never want to deliberately overflow a char by setting it to a negative value.

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533820

When you cast -1 to a char you get the 65535 character as char is an unsigned 16-bit integer. Whenever you cast a larger integer to a 16-bit value the lower 16-bit are retained. This is an invalid character by definition and thus will always print as ? or <?>

BTW (char) 255 is a valid character.

Upvotes: 1

Related Questions