Forum : Float data type use
Brief description  about Online courses   join in Online courses
View Sangita  Biswal 's Profile

Float data type use

Hi Everyone please help me out
class floatnum
{
public static void main (String args[])
{
float a=1.2;
System.out.println("The floating point number is :" " " a);
}
}
The above programme shows the following error at compile time
float a=1.2
possible loss of precision
Found: double
Required: float
Where and how can I use float data type
Asked by Sangita Biswal | Mar 13, 2010 |  Reply now
Replies (1)
View arun kumar das 's Profile
Hi Sangita,

Good Try! Let me explain you why you are getting the above error.

Here the java compiler is expecting double datatype but you have used float datatype.

In java all decimal numbers are by default taken as double datatype. This is because double holds the precise value of the decimal number and hence it needs more memory (64 bits). Whenever we need the precise value of a decimal number we use double datatype. In your sample programme you have initialised a=1.2 and you need precisely the value 1.2 be assigned to a. Here the java compiler gets a little confused as it is expecting double since you need precise value of decimal but you have given float.

Float datatype is used when precision is not a big factor in a decimal number. For Example: if you want to initialise pi which is 22/7=3.142857 you can do it in 2 ways.
Using double--> double pi=3.142857 - This precisely prints the value
Using float--> flaot pi=3.142857F - Here you use 'F' at the end of number to tell the compiler that you are not really bothered about the precision after .142857

Now try your program by initialising float a=1.2F and it should compile succesfully.

All this is done to save memory as float takes 32 bits and double takes 64 bits of memory.

Hope this has helped you...

Cheers...
Java Teacher (JT)
Mar 15, 2010