Reputation: 63
I am confused on why a float value has to be declared in the begging like any other value but then has to be declared right before the value.
Example: Float Z =(float)10.5;
Why cant we declare a float value as;
Example: Float Z = 10.5;
Upvotes: 3
Views: 302
Reputation: 23329
Because the same literal is used for representing doubles. 10.5 means double
which can't fit in a float.
You can express a float literal by appending 'f' or 'F' to the number as follows.
float z = 10.5F;
float z = 10.5f;
And because float fits in a double the opposite is not true.
double d = 10.5F; //works fine
Upvotes: 4
Reputation: 4809
Because 10.5
is a double
and it cannot be cast to float
implicitly.
You could define it without the explicit cast as
Float z = 10.5f;
Upvotes: 9
Reputation: 364
Floating point literals are double
s in Java.
To make it a float
you have to append an f
.
So that would be:
Float Z = 10.5f;
Upvotes: 6