krystah
krystah

Reputation: 3733

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?

Upvotes: 0

Views: 2344

Answers (4)

MariuszS
MariuszS

Reputation: 31567

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.

Upvotes: 1

Martin Seeler
Martin Seeler

Reputation: 6982

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.

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

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;

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074276

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.)

Upvotes: 3

Related Questions