posted 22 years ago
The result of any arithmetic operation on 2 ints will always be an int. The result value may or may not be mathematically correct though as any overflow / underflow is ignored and you simply get back the low order 32 bits of the result.
You can convert the integer result to another type by assigning it to a variable of that type, using a cast if necessary. However, any overflow or underflow will already be lost. Consider the following code:
<pre>
int i = (Integer.MAX_VALUE) + 5;
System.out.println(i); // -2147483644
long l = (Integer.MAX_VALUE) + 5;
System.out.println(l); // -2147483644 - same result as before!
</pre>
The result is the same even if you assign it to a long because the overflow was already lost. However, if you cast one of the operands to long, the whole result will be long (64 bits) and you won't lose any precision.
<pre>
long l = (long)(Integer.MAX_VALUE) + 5;
System.out.println(l); // 2147483652 - correct result
</pre>
[This message has been edited by JUNILU LACAR (edited July 09, 2001).]