Sorry for a beginners question! I am learning Java and I'm a bit confused on one topic.
For example, I am declaring and initializing a variable as a float such as:
float myVariable = 9.5;
In some tutorials online, I see floats being declared and initalized like that, but also with a suffix such as this:
float myVariable = 9.5F;
What is the purpose of the the suffix if I am already saying "float myVariable"?
Thanks!
Floating point literals are by default of double
type. So, 9.5
is double not float. To make it float we append an f
at the end.
So, in first case:
float myVariable = 9.5;
You are trying to assign a double type literal to a float type variable, which requires an explicit typecasting. The statement won't compile. You need to add a cast there:
float myVariable = (float) 9.5;
While in 2nd case:
float myVariable = 9.5F;
there is no conversion.
Java uses suffixes with these primitives types, here is a brief intro:
float
float fVariable = 5.5
is by default double while float fVariable = 5.5f
makes it float
long
long lVariable = 55
here literal 55 is by default int type but long lVariable = 55l
makes it long type.
double
double dVariable = 5.5
and double dVariable = 5.5d
are similar but here d suffix is optional
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With