File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A tricky problem 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 "A tricky problem" Watch "A tricky problem" New topic

A tricky problem

rituk Kapoor

Joined: Sep 01, 2005
Posts: 4
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;

Output is :

Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Karthik Hariharan
Ranch Hand

Joined: Aug 14, 2005
Posts: 31
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

Joined: Sep 01, 2005
Posts: 4
Thanks to both of you. Specially Barry.
I agree. Here's the link:
subject: A tricky problem
It's not a secret anymore!