The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Short cast to char - bungle Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Short cast to char - bungle" Watch "Short cast to char - bungle" New topic

Short cast to char - bungle

Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214

Why does my_byte (value 56) when cast to a char, givea value of 8?



SCJP 1.4 (93%)<br />SCJD (In progress. It can run, but it can't hide...)
levani dvalishvili
Ranch Hand

Joined: Mar 01, 2005
Posts: 99
decimal equvalent of char 8 is 56
since you are asigning a byte to a char it assumes a decimal char value and gives you number 8 .
[ April 10, 2005: Message edited by: levani dvalishvili ]

SCJP 1.5(Done) SCJA 1.0(Done)<br />SCWCD(in Progress...)
Simon Cockayne
Ranch Hand

Joined: Dec 09, 2000
Posts: 214

Thanks for the response.

Why is "decimal equvalent of char 8 is 56"?


marc weber

Joined: Aug 31, 2004
Posts: 11343

The char '8' is represented by the decimal value 56.

See the following ASCII table...

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Saurabh Khanna
Ranch Hand

Joined: Apr 03, 2005
Posts: 30
char is UNSIGNED 16 bit integral type where as byte is signed. The main point is that the 16 bits in char are used to represent characters according to UNICODE character set.

Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
can anyone explain the subtle diff between the char byte and short
Joe Sondow
Ranch Hand

Joined: Apr 10, 2005
Posts: 195
byte: 8-bit signed integer. Range -128 to 127.
short: 16-bit signed integer. Range -32768 to 32767.
char: 16-bit unsigned integer. Range 0 to 65535.

SCJA 1.0 (98%), SCJP 1.4 (98%)
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Another way of answering is that a char is a 16 bit unsigned number, while a short is a 15 bit number plus a one bit sign on the left. You may want to read up on two's complement binary notation, it is part of the SCJP exam syllabus.

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link: http://aspose.com/file-tools
subject: Short cast to char - bungle
Similar Threads
mock exam Q compile time constants
char c = (int) 1;
Casting hierarchy
implicit casting of final int to byte ???