• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A tricky problem

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If we are doing a operation like this(as shown below), we need to cast to char type. I'm getting the same output in both the case. Can anyone pls explain this to me.
1. what is actually happening at stage 1(commented)?
2. Why is it display "?" in both the cases?

byte b =-20;
short s= -34;
char c1 = (char)b; //1
char c2 = (char)s;
System.out.println(c1);
System.out.println(c2);

Output is :
?
?

Regards;
Ritu
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The eight bit representation of the byte containing -20 is "1110 1100" (the twos-complement representation of -20). At line //1 it is converted to a 16 bit wide char with sign extension: "1111 1111 1110 1100".

The ? is just an indicator that the character represented by the bit pattern cannot be printed on the output stream.

Try the following:


[ September 02, 2005: Message edited by: Barry Gaunt ]
[ September 02, 2005: Message edited by: Barry Gaunt ]
 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Barry is correct. There is a finite list of ASCII characters mapped to particular integer values. If you try to cast any integer outside this valid list of ASCII values, you will get a ? displayed.
 
rituk Kapoor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks to both of you. Specially Barry.
 
Just the other day, I was thinking ... about this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic