• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Explanation required - negative value given to char prints '?'

 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers

If we assign a negative value to a char variable using type cast and print the variable, it always prints '?'. Example -

char c = (char) -65;
System.out.println(c);

Output is -
?

Please explain why.. Thanks in advance.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15205
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A char in java is an unsigned 16-bit integer. If you cast a negative integer literal like -65 to a char, then the value is interpreted as a positive number; in this case 65471 - or Unicode character \uFFBF.

The character \uFFBF isn't a character which is normally displayable so a '?' is printed.
 
Mohit Jain
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The character \uFFBF isn't a character which is normally displayable so a '?' is printed.
--------------------

Hi Jesper

Thanks for clarification. What I understand is -

When a negative number is assigned to a char, it is interpreted into positive value as -

Total range of char (65536) - 65 = 65471

\uFFBF represents 65471 in unicode,

How can we compute the unicode representation of any given integer.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic