1

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
Maroun
  • 94,125
  • 30
  • 188
  • 241
jos
  • 1,082
  • 5
  • 19
  • 45

2 Answers2

4

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

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.

Robert Field
  • 479
  • 4
  • 5