Doubt about float data type in Java

2

I'm learning how to program, and I'm doing data type exercises. I'm supposed to find errors in the code, and here I am:

9.-  float f1 = 13.5; 
10.- float f2 = 8f;

I really have a bit of a mess, because I do not know if the failure is that every% float carries a f after the value as in the line of code 10, or that really should not carry that f because we do not have any variable that is called f , but f1 , and that f would mean: 8*f.

    
asked by Sergio 11.02.2018 в 19:03
source

2 answers

4

What happens is if declaring a variable of type float does not add the f (floating point literal) (ref) or cast to float is not done default will be double so in line 9 it would give an error of incompatibility of data type, since it would be necessary to realize the cast to be able to assign the value (two possible ways)

float f2 = 13.5; //Error , tipo double
float f2 = (float) 13.5; // correcto
float f2 = 13.5f; // correcto también
    
answered by 11.02.2018 / 20:01
source
1

Variables of type float allow to store real numbers, such as: 5.85, 7.0, 25.023... , that is, numbers with decimals.

To assign a value to a float type variable, you can either write the number directly, for example: 8 ; or add the suffix 'f' to the number: 8f , as in your example.

Therefore, consider it as two different ways of declaring a float variable.

    
answered by 11.02.2018 в 19:20