java - 将 long 显式转换为 int 并将 long 隐式转换为 float

标签 java casting type-conversion

public class Casting {
    public static void main(String[] args){
        int I = 1;
        long L = 1;
        float F = 1;
        double D = 1;

        L = I; // int always fits into long, no problem here
        I = L; // Error: Type mismatch: cannot convert from long to int
               // long not always can fit into int, so explicit casting is required. Seems logical.
               // But at the moment magnitude of L fits into I, and casting can be done without truncation 

        F = L; // This doesn't produce any error, and casting is done implicitly.
               // In this case magnitude of L also fits into F

    }
}

所以,问题是 - 为什么在 I = L 的情况下,当 L 的大小足够小以适合 I 时,必须明确地完成,但在 F = L 的情况下,其中 L 的大小也适合F,可以隐式进行转换而不会产生错误。

我的意思是,在这两种情况下,右操作数的大小可能不适合左操作数。 那么为什么在一种情况下(I=L)必须显式地进行转换,而在另一种情况下(F=L)则可以隐式地进行转换? 虽然将 long var 隐式转换为 int var 看起来比将 long var 隐式转换为 float var 更自然。(假设值足够小以适合彼此)

希望我能够表达我想要理解的内容。

最佳答案

Long.MAX_VALUE = (2^63)-1
Float.MAX_VALUE= 2^127
因此,Long 值始终适合 Float 值。
编译器不会分析代码中的实际值。它从不验证该值是否适合。

关于java - 将 long 显式转换为 int 并将 long 隐式转换为 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21330895/

相关文章:

c - 为什么当我不转换 malloc 的结果时编译器会报错?

c - AVR GCC - 类型转换问题

c++ - 不使用内置函数(如 atoi 或 atof)将字符串转换为 float 或整数

URL 的 MySQL 数据类型

Java Swing Worker 导致 GUI 卡住

java - 避免不必要的检查

java - 机器小量

java.sql.Date 不打印正确的日期

c++ - 将 const char * const 参数的成员分配给新值

c++ - 基于策略的类中的策略转换运算符与私有(private)析构函数