简体   繁体   中英

Explicit casting a long into an int and implicit casting a long to a float

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

    }
}

So, the question is - why in case of I = L, when the magnitude of L small enough to fit I, it has to be done explicitly, but in case of F = L, where magnitude of L also fits into F, the casting can be done implicitly without producing an error.

What I mean is that in both cases it's possible that the magnitude of right operand may not fit into left operand. So why in one case (I=L), casting has to be done explicitly, but in another (F=L) it can be done implicitly? Although implicitly casting of long var to int var would seem more natural than implicitly casting of long var to float var.(assuming that values small enough to fit each other)

Hope I was able to express what I want to understand.

Long.MAX_VALUE = (2^63)-1
Float.MAX_VALUE= 2^127
So, Long value always fits into Float value.
Compiler doesn't analyse real values from your code. It never verifies if the value may fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM