wood burning stoves
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes casting variables 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 "casting variables" Watch "casting variables" New topic

casting variables

alwin das
Ranch Hand

Joined: Sep 23, 2005
Posts: 32

int is 32 bit and float is also 32 bit

long is 64bit and double is also 64bit

but when i try to assign float value(variable) to int(w/o explicit cast) it gives compile time error same is case with long,when i try to assign double value to long variable(w/o explicit cast),it flags a error.

but when i assign int value to float or long value to double ,there is no error and values are casted implicitly..

why it is like that?
marc weber

Joined: Aug 31, 2004
Posts: 11343

A 32-bit float has greater range than a 32-bit int. But to get that range, it gives up "precision."

Think of float and double storage as a type of scientific notation. It might take less space to store something in an approximate form of 1.1e9 compared to an exact form of 1123456789, but the latter is obviously more precise. Now, if we "force" 1.1e9 into the second form, we get 1100000000, which is close to 1123456789, but has introduced zeros as placeholders, which are not precise.

So in going from float to int, an explicit cast is required to acknowledge that you understand the result might not be exact.

Note: This is why you also need an explicit cast going from a 32-bit float to a 64-bit long.
[ June 14, 2006: Message edited by: marc weber ]

"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
alwin das
Ranch Hand

Joined: Sep 23, 2005
Posts: 32
thank you very much for the explanation
I agree. Here's the link: http://aspose.com/file-tools
subject: casting variables
jQuery in Action, 3rd edition