Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does java force me to add f when I use float?

Tags:

java

I'm very new to programming. I have the following code:

float f = 18.45f;

this works fine. If I change that to:

float f = 18.45;

java saying this as error:

error: possible loss of precision

But its optional in terms of double. But in long again I'm facing the same problem.

Why does java forces me to do so, but not in case with double?

like image 455
sriram Avatar asked Feb 24 '13 17:02

sriram


People also ask

Why do we write F after float variable in Java?

Why is it used? The "F" indicates that the literal numeric value it is appended to is a float value. This is necessary information for the compiler and if not present can lead to errors or the compiler otherwise interpreting the number incorrectly.

Can we declare float without F in Java?

float variables can be represented with a lowercase 'f' OR uppercase 'F' at the end, which asks the program specifically for a single-precision float literal which deals with a 32 bit floating point. Even without the 'f' or 'F' at the end the program, it assumes a float is declared and initialized.

Why float is not used in Java?

Java does not use it as the default floating-point number. It is the default data type for floating-point numbers. There will be no data loss if we convert float to double. There will be data loss if we convert double to float.


1 Answers

In Java, 18.45 is a double data type which holds 64-bit. float data type can hold up to 32-bit only. Adding the extra f makes it a float (float literal).

See Primitive Data Types for more details.

like image 161
Eng.Fouad Avatar answered Sep 28 '22 05:09

Eng.Fouad