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
• Ron McLeod
• Tim Cooke
• Liutauras Vilda
• Jeanne Boyarsky
Sheriffs:
• Paul Clapham
• Rob Spoor
• Junilu Lacar
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Piet Souris
• Carey Brown
Bartenders:

# Primitive casting

Greenhorn
Posts: 24
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 1710
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
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
• Number of slices to send:
Optional 'thank-you' note:
I made typo in my previous post giving you range float can hold, I have edited my post.

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 ]

 Consider Paul's rocket mass heater.