简体   繁体   中英

Java: Casting long to int

Let's assume the variables start and stop are both long-type variables.

int diff = (int) start-stop;

This code yields the error Type mismatch: cannot convert from long to int , while

int diff = (int) (start-stop);

runs as expected. Why?

Because in the first, the (int) applies to start , not the expression, like this:

int diff = ((int) start) - stop; // <== Your first expression clarified

Then you subtract a long from the resulting int , and the result of that expression is a long . (If it had worked, it probably would have had the side-effect of giving you an incorrect result, if start ever has values that are too big to store in an int .)

By first doing the subtraction and getting the long result, then casting that to int , you can store it in your int variable. (Presumably you know it'll fit from your application logic.)

Because Java doesn't allow implicit narrowing conversions. One would be required in the first case, as it's equivalent to:

int diff = ((long)(int)start) - stop;
int diff = (int) start - stop;

is equal to

int diff = (int) (long) start - (long) stop; // we substract long types

can be simplified to

int diff = (int) start - (long) stop; // (int)(long) x means (int) x

is equal to

int diff = ((int) start) - (long) stop; // casting is applied only to start

is equal to

int diff = ((long)(int) start) - (long) stop; // compiler make types equal

can be simplified to

int diff = (long) start - (long) stop; // we can substract now

is equal to

int diff = (long) startMinusStop; // because long - long => long

and here we are readable error Type mismatch: cannot convert from long to int .

In your first statement you will only cast the variable start to an integer. So the result is int - long which is a long and does not fit in an integer.

it will be like int = (int - long) and java will not allow.

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