Java: double vs float

后端 未结 6 1202
一整个雨季
一整个雨季 2020-12-09 16:37

In another Bruce Eckel exercise, the code I\'ve written takes a method and changes value in another class. Here is my code:

class Big {
  float b;
}

public         


        
6条回答
  •  半阙折子戏
    2020-12-09 17:02

    can't doubles be floats as well?
    

    No. Each value or variable has exactly one type (double, float, int, long, etc...). The Java Language Specification states exactly what happens when you try to assign a value of one type to a variable of another type. Generally, assignments of a "smaller" value to a "larger" type are allowed and done implicitly, but assignments where information could be lost because the target type is too "small" to hold all values of the origin type are not allowed by the compiler, even if the concrete value does fit into the target type.

    That's why the compiler complains that assigning a double value (which the literal implicitly is) to a float variable could lose information, and you have to placate it by either making the value a float, or by casting explicitly.

    One area that often causes confusions is calculations, because these are implicitly "widened" to int for technical reasons. So if you multiply two shorts and try to assign the result to a short, the compiler will complain because the result of the calculation is an int.

提交回复
热议问题