Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

long -> float conversion

 
Vishy Karl
Ranch Hand
Posts: 116
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello friends,

see the foll. code snippet.
long l = 5; // 1
float f = l; // 2 This compiles fine!!!
l = f; // 3 This gives compiler error !!!
But as we know that long is 64 bits(8 bytes) & float is 32 bits(4 bytes).
Then how is the statement at line 2 valid without any casting??
and statement at line 3 gives error ? I was expecting the behaviour to be the other way.
Thanx in advance.
 
Yi Meng
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vishy Karl:

But as we know that long is 64 bits(8 bytes) & float is 32 bits(4 bytes).

The meaning for these bits are different. for long, you know that the max is 2^63 - 1 whereas for float, its 32 bits are conform to the IEEE 754 standard. Just google "IEEE 754" and you will find lots of info about the standard and particularly the bit representation. in short, the range that a float can represent is far wider than long ....that's why a long can be implicitly cast to float and not vice versa.
you may just use the link i find for you here. http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic