• Post Reply Bookmark Topic Watch Topic
  • New Topic

Primitive casting  RSS feed

 
Rohan Pujari
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
long in java is 64bits whereas float is 32 bits.
so i wrote a very simple code like this

long l = 1256L;
float f = 25.25F;

how does a long fit into a long and why does the compiler give error while putting float into long.

could some one please let me know the exact details about float and double data types like how many bits are used to represent the the digits before the decimal point and those after the decimal point.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Rohan,

Converting a long to a float is a widening conversion.
Although this is well known fact that
1- long takes 64 bits
2- float takes 32 bits

A number long can hold, float can easily hold but vice versa is not true.
That is why if you assign a long value to the float, it is widening conversion but for vice versa you do narrowing conversion so explicit casting is required.

Dont go with how many bits one takes in this scenario rather you should look at what range of values float and long can contain. float can contain a very huge range of value because number is represented in scientific notation.
See very small example how numbers can be stored in this way:

10000 = 10 * 10^3
100000 = 10*10^4
and so on


The largest number a long can have is 2^63 - 1. Whereas, a float, which is 32 bits shorter than a long, can have up to (2-2^-23)�2^127.

Thanks and Regards,
cmbhatt
[ April 07, 2007: Message edited by: Chandra Bhatt ]
 
Rohan Pujari
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help.

But how did you get that figure for the float storage
The largest number a long can have is 2^63 - 1. Whereas, a float, which is 32 bits shorter than a long, can have up to (2-2^23)�2^127.


it would be good if you could elaborate on that.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I made typo in my previous post giving you range float can hold, I have edited my post.
Please update yourself too!


static float MAX_VALUE
A constant holding the largest positive finite value of type float, (2-2^-23)�2^127.

static float MIN_VALUE
A constant holding the smallest positive nonzero value of type float, 2^-149.

Source



Won't be it better if we try to remember upto this level only?



Regards,
cmbhatt
[ April 07, 2007: Message edited by: Chandra Bhatt ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!