Ioanna Katsanou Ioanna Katsanou - 1 month ago 19
Java Question

Different Data Types Operations double-float

I know that when having to do with operators in Java , and different data types, then the result is promoting to the larger of the data types
So, because double is larger than float, when having for example

double z=39.21;
float w=2.1F;
System.out.println(z+w );

The result z+w will be of double type.
If I don't put the F on the float data type, then the float is assumed to be double.

So why the below code does not compile??

double z=39.21;
float w=2.1;
System.out.println(z+w );

Shouldn't the result just be double, if both z and w are considered double???
Instead it throws: error: incompatible types: possible lossy conversion from double to float
float w=2.1;
1 error

Also, when

short x = 14;
float y = 13;
double z = 30;
System.out.println( x * y / z);

First, the short gets converted to int. Then the int gets converted to Float. Then multiplication happens.

Why does in this case compile , since we have an operation between a double and a float without an F??????

I cannot seem to understand that case can you help me?

float w = 2.1;  // error

By default, 2.1 is a Double literal.

Compiler wants an assurance from your side that you're ready to perform the narrowing conversion, that's why it expects a F (or f) after the literal.

If you don't put an F(OR f), it will result in compilation error.

float y = 13;   // works successfully.

Whereas, in the other case, 13 is an Integer literal. So, it easily gets into a float type. Therefore, the code works successfully.