Casting int to long

I have a question about converting from int to long in java. Why there are no problems for floats:

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

      

However, for a long type, this 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 looks like when the compiler notifies an error due to an out-of-range problem, it blocks it without checking the possible casting that the programmer was planning.

What do you undertake? Why is this so, is there a special reason?

Thanks in advance.

+3


source to share


2 answers


Java doesn't account for what you are doing with the meaning of only what is. For example, if you have a long value that is too large, it doesn't matter what you assign to the double, the last value is checked first as valid.



+4


source


However, for a long type, this seems to be a problem:

This is because 12213213213

without L

is int

, not long

. And since this value is out of range int

, you will get an error.

Try something like: -

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

      

you will understand better.

As for the case float

: -

float f = (float)45.45;

      



value 45.45

is value double

and corresponds to size double

. This way the compiler will have no problem with it and then it will execute from cast

to float

.

It seems that after the compiler notifies an out-of-range error, it blocks it without checking for any possible casting that the programmer may have planned.

Quite right. The compiler first checks for the correct value here int

, only then it can move on with the casting operation.

So basically in case long

and int

: -

long l = (long)12213213213;

      

you are not getting an error because of the operation cast

, but because yours is numeric literal

not represented as int

. Thus, the compiler did not get a valid value to perform the casting operation.

+8


source







All Articles