float variables initialization java

前端 未结 6 1097
面向向阳花
面向向阳花 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:19

    should be

    float density = 20.0f;
    
    0 讨论(0)
  • 2021-01-23 04:33

    As per my understanding, float is used for decimal variables.

    No. Numerical literals with fraction parts are treated as doubles by default.

    0 讨论(0)
  • 2021-01-23 04:35

    float density = 20.0f;

    If you try to assign a decimal number you must place an "f" at the end, otherwise Java will assume you are trying to assign a double .A double would more precisely cover more numbers that you could type in.

    0 讨论(0)
  • 2021-01-23 04:39

    In Java by default decimal values are stored as double. But for storing it as a floating point number we explicitly need to declare, like

    float varName = 10.0f; or float varName = (float)10.0;

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-23 04:45

    Per the JLS, §3.10.2, all floating point literals are interepreted as double unless specified as a float.

    A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).

    Change your declaration to:

    float density = 20.0f;
    

    In general, consider why you're using float - it has less precision than double, and isn't used nearly as often.

    0 讨论(0)
提交回复
热议问题