I was trying Java9 feature JShell. I'm not able to set a float value:
jshell> float b = 3.5
Error:
| incompatible types: possible lossy conversion from double to float
| float b = 3.5;
jshell> float x =2
x ==> 2.0
I was trying Java9 feature JShell. I'm not able to set a float value:
jshell> float b = 3.5
Error:
| incompatible types: possible lossy conversion from double to float
| float b = 3.5;
jshell> float x =2
x ==> 2.0
It's Java being unduly pernickety.
The type of the literal 3.5
is a double
, and you are assigning that to a float
.
Since the set of possible float
s is necessarily a subset of the set of possible double
s, you get a precision lost on conversion warning.
For an easy life, use 3.5f
to denote a float
literal.
But note that 3.5
can be represented exactly in both a double
and float
, so on this specific occasion, the error is hogwash.
This is the behaviour of Java (as described in the existing answer). JShell follows Java syntax and semantics exactly -- this is important so you don't develop incorrect code.