likeIT
likeIT

Reputation: 307

strange behaviour of the java

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

Answers (3)

asgs
asgs

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

Pablo Santa Cruz
Pablo Santa Cruz

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

Oliver Charlesworth
Oliver Charlesworth

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

Related Questions