wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Explanation required - negative value given to char prints '?' Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Explanation required - negative value given to char prints Watch "Explanation required - negative value given to char prints New topic
Author

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

Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
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.


SCJP 5.0, SCWCD in progress
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Mohit Jain
Ranch Hand

Joined: Jun 04, 2007
Posts: 74
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Explanation required - negative value given to char prints '?'