Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

casting variables

 
alwin das
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

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
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
alwin das
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you very much for the explanation
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic