• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

casting variables

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thank you very much for the explanation
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic