Question

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!

Was it helpful?

Solution 2

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

OTHER TIPS

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.

Have you tried to compile your code?

This will not compile, because by default all floating-point literals are doubles

float myVariable = 9.5;

You can use explicit cast operation

float myVariable = (float) 9.5;

But it's too verbose, so thankfully the 'F' suffix was introduced:

float myVariable = 9.5F;

BTW, both UPPER ('F') and lower ('f') cases are allowed.

Thought it might be worth providing an answer that cites the specification. From §3.10.2 Floating-Point Literals:

A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double...

In other words, 9.5 and 9.5f are two distinct literals with different types.

  • 9.5 is of type double and cannot be assigned to a float without explicit casting
  • 9.5f is of type float (and as such can obviously be assigned to a variable of type float)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top