Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# Primitive Casting

Srinivasa Raghavan
Ranch Hand
Posts: 1228
Hi all,
How to approach the following type of problems when asked in any exams.

To be more clear how to calculate "(short)32768" manually.
[ March 08, 2005: Message edited by: Srinivasa Raghavan ]

David Harkness
Ranch Hand
Posts: 1646
Write out a short list (no pun intended) of the minimum and maximum values for byte, short, and int and memorize it. I've memorized them simply from reading and typing them over the last 20 years, but even still I only know the maximum int to a few decimal places (2.147 billion something).

My apologies if this offends anyone, but this is one of the reasons I've never valued certification tests all that highly. I've met too many SCJPs that can barely code themselves out of a paper bag, yet they can quote JLS rules 'til they're blue in the face. And yes, I understand that it is very difficult to design tests for thousands of people to take world-wide without falling back on memorization as a key component. *sigh*

I just wish I could take the SCJD without taking the SCJP first. I know, skip dinner and go right for dessert, naughty boy!
[ March 08, 2005: Message edited by: David Harkness ]

Marilyn de Queiroz
Sheriff
Posts: 9064
12
Hopefully people will find the SCJP exam for Java 5 more challenging.

Surasak Leenapongpanit
Ranch Hand
Posts: 341
short has range in [-32768, 32767].

32768 = 1111 1111 1111 1111
then,
(short) 32768 = -32768
because the left most bit is sign bit, so 1 is negative number.

David Harkness
Ranch Hand
Posts: 1646
I really didn't mean to hijack the thread -- I even answered the question at the start.

Other helpful advice would be to get familiar with hexadecimal numbers and how negative values are represented. Off the top of your head you should be able to write the minimum and maximum values for any of the integer types.Quick, which values above come first: minimum or maximum?

David Harkness
Ranch Hand
Posts: 1646
Originally posted by Surasak Leenapongpanit:
32768 = 1111 1111 1111 1111
Actually, that binary number equals -1 (as a short) or 65535 (as an int).

int 32768 = 0x00008000 = 0000 0000 0000 0000 1000 0000 0000 0000.

The lower half of the binary number equals -32768 when cast to a short since the high bit is the sign, as Surasak stated.