显式地将一个long转换为int并隐式转换long为float

时间:2014-01-24 10:59:11

标签: 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更自然(假设值小到足以相互适应)

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

1 个答案:

答案 0 :(得分:4)

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