Reputation: 307
hello I have some question about java, why the following code return strange value?
System.out.println("Strange " + (20 * 232792560)/20);
why do I recieve 18044195
?
Upvotes: 2
Views: 103
Reputation: 3984
Because (20 * 232792560)
will perform integer based multiplication and the result is obviously out of int
's range, hence the value will be truncated.
Upvotes: 1
Reputation: 181460
Because 20 * 232792560
does not fit in 4 bytes (integer value).
So you got:
20 * 232792560 = 360883904; // because of int overflow
360883904 / 20 = 18044195;
Upvotes: 0
Reputation: 272752
Because (20 * 232792560)
overflows the range of an int
, and wraps round the number range several times to become 360883904
. That is then divided by 20
to give you the result that you see.
If you want the correct result, then you need to do:
System.out.println("Strange " + (20 * 232792560L) / 20);
(Marking a literal with an L
means that the constant maths will be done with long
, rather than with int
, so this will no longer overflow.)
Upvotes: 5