JShell possible lossy conversion from double to float

334 views Asked by At

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
2

There are 2 answers

1
Bathsheba On BEST ANSWER

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 floats is necessarily a subset of the set of possible doubles, 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.

0
Robert Field On

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.