This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
So, I'm reading about casts which is a subject that I find odd and was wondering if anyone knew of a resource where I could find say a table or explicit list of what primitives require an explicit cast statement when their operated on ie
Ideally I'd like to print the sucker out and stick it on my wall next to my Precedence of Operators table. Any ideas? [ June 17, 2008: Message edited by: Tristan Rouse ]
Ashish Hareet
Ranch Hand
Joined: Jul 14, 2001
Posts: 375
posted
0
Tristan,
The simplest rule to follow with primitive casting is that the result of an arithmetic operation(excluding ++ & -- operators) will atleast be of type int or of the larger primitive type used in the operation.
class Casting { public static void main (String [] args){ long ln = 130L; byte by = (byte) ln; System.out.println ("\n Casting value is: "+by); } }
The answer is: -126 My question is: how does it works conceptually? means how does jvm handles this code if long is greater that 127 (byte value limit)
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
Welcome to JavaRanch, Yoogesh Patil.
Please don't ask new questions on somebody else's thread.
If you write out the bits for 130 in 16 bits, which are the same as a long only with fewer 0s, you get 0000 0000 1000 0010. When you cast to a byte you lose all but the rightmost 8 bits, leaving 1000 0010. In two's complement that is -126.
If you want any more information please start a new thread. [ June 25, 2008: Message edited by: Campbell Ritchie ]