Casting an int into a long

2019-07-04 17:07发布

问题:

I have a question regarding the conversion from int into long in java. Why for floats there is no problem:

float f = (float)45.45;//compiles no issue.
float f = 45.45f; //compiles no issue.

However for the long type it seems to be a problem:

    long l = (long)12213213213;
    //with L or l at the end it will work though. 
    long l = (long)12213213213L;

It seems that once the compiler notify an error due to an out-of-range issue it blocks there without checking for any possible casting that the programmer might have planned.

What's your take on it? Why is it like that there is any particular reason?

Thanks in advance.

回答1:

Java doesn't consider what you do with a value only what it is. For example if you have a long value which is too large it doesn't matter that you assign it to a double, the long value is checked as valid first.



回答2:

However for the long type it seems to be a problem:

That's because 12213213213 without L is an int, and not long. And since that value is outside the range of the int, so you get an error.

Try something like:-

System.out.println(Integer.MAX_VALUE);
System.out.println(12213213213L);

you will understand better.

As far as the case of float is concerned: -

float f = (float)45.45;

the value 45.45 is a double value, and fits the size of double. So, the compiler will have not problem with that, and then it will perform a cast to float.

It seems that once the compiler notify an error due to an out-of-range issue it blocks there without checking for any possible casting that the programmer might have planned.

Exactly. The compiler first checks for a valid value first, here int, only then it can move further with the cast operation.

So, basically in case of long and int: -

long l = (long)12213213213;

you are not getting error because of the cast operation, rather because your numeric literal is not representable as int. So, compiler didn't get the valid value there, to perform a cast operation.