• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Paddy spent all of his days in the O'Furniture back yard with this tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic