float variables initialization java

前端 未结 6 1164
面向向阳花
面向向阳花 2021-01-23 04:17

The following code snippet gave me compiler error at Line 1.

public abstract class xyz
{

    float Gamma = 20.0; //Line 1
    public class Alpha
    {
        v         


        
6条回答
  •  甜味超标
    2021-01-23 04:43

    Floating-point literals are considered doubles unless you specify that they're just floats. (Similarly, integer literals are ints unless specified otherwise.) Append the letter f to the number to make it a float:

    float density = 20.0f;
    

    The JLS has comprehensive typing rules for literal values. No, you don't have to make the literal a float with f, but then you have to cast it with (float) if you want to fit it in a float variable, since Java won't automatically try to shove a number of one type into a variable with a smaller range.

提交回复
热议问题