Why are there so many floats in the Android API?

前端 未结 5 1022
梦谈多话
梦谈多话 2021-02-07 09:46

The default floating point type in Java is the double. If you hard code a constant like 2.5 into your program, Java makes it a double automatically. When you do a

5条回答
  •  孤街浪徒
    2021-02-07 10:13

    I think Roman is correct, that the reason is likely mostly intended to reduce memory usage. Consider that when ultimate precision isn't important you will halve the memory needed for numeric variables.

    Remember though that it isn't necessary to use casting. Simply append an F to your literal (so 2.5 becomes 2.5f). I don't know if the compiler is smart enough to do the following substitution for you, but if not, this will make your code slightly more efficient as well.

    Consider

    float x = (float) 2.5;
    

    and

    float x = 2.5f;
    

    In the first case, at run time, the program stores a double, then carries out a cast operation, before storing the resulting float value. In the second case the compiler will recognize the value as a float, so at run time you avoid both the storing of a double (however temporarily that might be) and also avoiding the cast operation (since it is already stored as a float).

提交回复
热议问题