0

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?

2

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.