Jakob991
Jakob991

Reputation: 63

Why does a float value have to be declared twice?

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;

http://prntscr.com/a3c7i7

Upvotes: 3

Views: 302

Answers (3)

Sleiman Jneidi
Sleiman Jneidi

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

radoh
radoh

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

Matias SM
Matias SM

Reputation: 364

Floating point literals are doubles in Java. To make it a float you have to append an f.

So that would be:

Float Z = 10.5f;

Upvotes: 6

Related Questions