• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A tricky problem

 
rituk Kapoor
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • 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
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • 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 ]
 
Karthik Hariharan
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • 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
  • Quote
  • Report post to moderator
Thanks to both of you. Specially Barry.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic